Twiddling those bits in Python and mind those bit errors
Python provide the code writer the opportunity to drive right into the bits, and isolate bits. A standard method that we use to determine if a bit position (b0, b1, b2 or b3 in a value of val) is a '1' or a '0' is:
b0 = ((val) & 0x1) >> 1
b1 = ((val) & 0x2) >> 2
b2 = ((val) & 0x4) >> 3
b3 = ((val) & 0x8) >> 4
b4 = ((val) & 0x10) >> 5
Where we bitwise AND the value with the mask (0x1 represents 0000 0001 in binary), and then shift the bits by the bit position to move the masked bit down to the least significant bit. In this way the result is either a '0' or a '1'. So let's take an example used in serial communication.
Twiddling bits - VRC
Serial communications often uses vertical redundancy checking (VRC) where it adds a parity bit to the transmitted character. Longitudinal (or horizontal) redundancy checking (LRC) adds a parity bit for all bits in the message at the same bit position. Vertical coding operates on a single character and is known as character error coding. Horizontal checks operate on groups of characters and described as message coding.
LRC always uses even parity and the parity bit for the LRC character has the parity of the VRC code. In the example given next, the character sent for LRC is thus 10101000 (28h) or a ‘(’. The message sent is ‘F’, ‘r’, ‘e’, ‘d’, ‘d’, ‘y’ and ‘(’.
Without VRC checking, LRC checking detects most errors but does not detect errors where an even number of characters have an error in the same bit position. In the previous example if bit 2 of the ‘F’ and ‘r’ were in error then LRC would be valid. This problem is overcome if LRC and VRC are used together.
With VRC/LRC the only time an error goes undetected is when an even number of bits, in an even number of characters, in the same bit positions of each character are in error. This is of course very unlikely. On systems where only single-bit errors occur, the LRC/VRC method can be used to detect and correct the single-bit error. For systems where more than one error can occur it is not possible to locate the bits in error, so the receiver prompts the transmitter to retransmit the message.
A communications channel uses ASCII character coding and LRC/VRC bits are added to each word sent. Encode the word ‘Freddy’ and, using odd parity for the VRC and even parity for the LRC; determine the LRC character.
Here is a Web page and Pythong code which implements the LRC calculation: