What are 0x01 and 0x80 representative of in C bitwise operations?

0x01 is the least significant bit set, hence the decimal value is 1.

0x80 is the most significant bit of an 8-bit byte set. If it is stored in a signed char (on a machine that uses 2’s-complement notation – as most machines you are likely to come across will), it is the most negative value (decimal -128); in an unsigned char, it is decimal +128.

The other pattern that becomes second nature is 0xFF with all bits set; this is decimal -1 for signed characters and 255 for unsigned characters. And, of course, there’s 0x00 or zero with no bits set.

What the loop does on the first cycle is to check if the LSB (least significant bit) is set, and if it is, sets the MSB (most significant bit) in the result. On the next cycle, it checks the next to LSB and sets the next to MSB, etc.

| MSB |     |     |     |     |     |     | LSB |
|  1  |  0  |  1  |  1  |  0  |  0  |  1  |  1  |   Input
|  1  |  1  |  0  |  0  |  1  |  1  |  0  |  1  |   Output
|  1  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |   0x80
|  0  |  0  |  0  |  0  |  0  |  0  |  0  |  1  |   0x01
|  0  |  1  |  0  |  0  |  0  |  0  |  0  |  0  |   (0x80 >> 1)
|  0  |  0  |  0  |  0  |  0  |  0  |  1  |  0  |   (0x01 << 1)

Leave a Comment