Home > Software design >  What does this code does ? There are so many weird things
What does this code does ? There are so many weird things

Time:09-29

int n_b ( char *addr , int i ) {
    char char_in_chain = addr [ i / 8 ] ;
    return char_in_chain >> i%8 & 0x1;
}

Like what is that : " i%8 & Ox1" ?

CodePudding user response:

Edit: Note that 0x1 is the hexadecimal notation for 1. Also note that :

0x1 = 0x01 = 0x000001 = 0x0...01

i%8 means i modulo 8, ie the rest in the Euclidean division of i by 8.

& 0x1 is a bitwise AND, it converts the number before to binary form then computes the bitwise operation.

Example : 0x1101 & 0x1001 = 0x1001

Note that any number & 0x1 is either 0 or one.

Example: 0x11111111 & 0x00000001 is 0x1 and 0x11111110 & 0x00000001 is 0x0

Essentially, it is testing the last bit on the number, which is also called the parity bit.

Any even number has 0 as it's last bit, and any odd number has 1.

The code is checking if i % 8 is odd. If it is, the code will shift char_in_chain to the right by one.

If not, it will not shift it and will return it.

It's difficult to say what it really does without better context.

Edit 2: Right Shift has priority on modulo, so the code will first shift by i, then compute the modulo 8, then perform the bitwise AND.

Since the last operation is a bitwise AND by 0x1, the code will either return 1 or 0.

CodePudding user response:

The function checks whether or not a specific bit in a char variable is set. If the bit is set the function return 1, otherwise it returns 0.

Like:

i == 0 : Check if bit 0 is set
i == 1 : Check if bit 1 is set
i == 2 : Check if bit 2 is set
i == 3 : Check if bit 3 is set
i == 4 : Check if bit 4 is set
i == 5 : Check if bit 5 is set
i == 6 : Check if bit 6 is set
i == 7 : Check if bit 7 is set

Due to use of the remainder operator %, i.e. i%8 the pattern above repeats for higher values of i

Like:

i == 8  : Check if bit 0 is set
i == 9  : Check if bit 1 is set
i == 10 : Check if bit 2 is set
i == 11 : Check if bit 3 is set
i == 12 : Check if bit 4 is set
i == 13 : Check if bit 5 is set
i == 14 : Check if bit 6 is set
i == 15 : Check if bit 7 is set

i == 16 : Check if bit 0 is set
i == 17 : Check if bit 1 is set
i == 18 : Check if bit 2 is set
and so on

Now the char variable that is being checked is read from a char array using i/8 as index.

That means that i in range 0..7 will check the same variable (i.e. array index 0) but look at different bits of that variable.

That means that i in range 8..15 will check the same variable (i.e. array index 1) but look at different bits.

and so on...

Now if you consider the char array as a single variable with bit number going from 0 to N * 8 (Where N is the number chars in the array), you can say that the function checks if th i'th bit is set.

  •  Tags:  
  • c
  • Related