Advertisement
prabhavms

checksum

Nov 19th, 2024
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | Source Code | 0 0
  1. def ones_complement(value, bits):
  2.     mask = (1 << bits) - 1
  3.     return (~value) & mask
  4.  
  5. def binary_sum(frames, bits):
  6.     total = sum(int(frame, 2) for frame in frames)
  7.     while total >> bits:  # Handle carry
  8.         total = (total & ((1 << bits) - 1)) + (total >> bits)
  9.     return total
  10.  
  11. def sender(frames, bits):
  12.     total = binary_sum(frames, bits)
  13.     checksum = ones_complement(total, bits)
  14.     data_to_send = frames + [f'{checksum:0{bits}b}']
  15.     print("\nSender Side:")
  16.     print("Total Sum (Binary):", f'{total:0{bits}b}')
  17.     print("Checksum (1's complement):", f'{checksum:0{bits}b}')
  18.     print("Data to be sent:", ' '.join(data_to_send))
  19.     return data_to_send
  20.  
  21. def receiver(received_frames, bits):
  22.     total = binary_sum(received_frames, bits)
  23.     calculated_checksum = ones_complement(total, bits)
  24.     print("\nReceiver Side:")
  25.     print("Received Frames:", ' '.join(received_frames[:-1]))
  26.     print("Received Checksum:", received_frames[-1])
  27.     print("Total Sum (Binary):", f'{total:0{bits}b}')
  28.     print("Calculated Checksum (After Adding Received Checksum):", f'{calculated_checksum:0{bits}b}')
  29.     print("Status:", "Approved (No Error)" if calculated_checksum == 0 else "Discarded (Error)")
  30.  
  31. # Input
  32. K = int(input("Enter the number of frames to transmit (K): "))
  33. N = int(input("Enter the number of bits in each frame (N): "))
  34. frames = [input(f"Enter frame {i+1} ({N} bits): ") for i in range(K)]
  35.  
  36. # Sender Side
  37. data_to_send = sender(frames, N)
  38.  
  39. # Receiver Side
  40. receiver(data_to_send, N)
Tags: checksum
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement