What do 0x01 and 0x80 represent in C bitwise operations?

I am trying to reorder the bits in C (homework, topic: bitwise operators). I found this solution, but I am a little confused by the hex values ​​used - 0x01 and 0x80.

  unsigned char reverse(unsigned char c) {
     int shift;
     unsigned char result = 0;

     for (shift = 0; shift < CHAR_BITS; shift++) {
        if (c & (0x01 << shift))
            result |= (0x80 >> shift);
     }
     return result;
  }

The book I'm working on did not discuss these kinds of values, so I'm not quite sure what to do with them. Can someone shed some light on this decision? Thank!

+5
source share
4 answers

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

0x80 8 . char ( , 2), , , , , (decimal -128); unsigned char, +128.

, , 0xFF ; -1 255 . , , 0x00 .

, , ( ), , MSB ( ) . LSB MSB ..

| 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)
+4

4 ,

  • 0x01 - 1.
  • 0x80 - [1000] [0000] 128.

.

:

if (a & b) { ... }

"...", 1 "a" "b".

c |= b

'c' 1, 1 'b'.

.

!

+3

0x01 1, , 0x80 128 - 8 . . .

: , . , - (0x1 = 1), - (0x10 = 16), - (0x100 = 256) .

0

0x01 0x80 , unsigned char.

:

  • CHAR_BITS : CHAR_BIT.
  • CHAR_BIT 8 , 0x80 , CHAR_BIT == 8.
  • there is another subtle portability problem: it 0x01 << shiftwill have undefined behavior for shift = CHAR_BIT-1on the platform, where sizeof(unsigned char) == sizeof(int)because it 0x01has a type int(and not unsigned int, counter-intuitive, isn’t it?).

Here is the patched version that works on all compatible platforms:

#include <limits.h>

unsigned char reverse(unsigned char c) {
    int shift;
    unsigned char result = 0;

    for (shift = 0; shift < CHAR_BIT; shift++) {
        result <<= 1;
        result |= c & 1;
        c >>= 1;
    }
    return result;
}
0
source

Source: https://habr.com/ru/post/1741617/


All Articles