C language left and right

Things happen:

There is a one day work needs to be saved to a different value of the char and the first 4 bits 4 bits.

Colleagues have made exactly the same as a first 8 bits of 32-bit code value of int:

// obtain the 32-bit values of eight bits high 
#define U32_HIGH_8 (Val) ((Val >> 24) & 0x000000ff)

Curiosity came in right after 24 whether there is a need and then on (&) 0x000000FF will completely clear the high data?

discuss:

Consider the following questions:

(1)

char i = 0x40 ; // binary representation for i: 0100 0000 

unsighed char j = 0x40 ; 

i << = 1 ; 

j << = 1 ; 

// Q: i and j are equal to how much?

i left after binary representation: 1000 0000, defined by a signed char interpreted as: i = -128

J left after binary representation: 1000 0000, defined by unsigned (unsigned char) interpreted as: i = 128

(2)

char i = 0x80 ; // binary represented as: 1000 0000 

char j = 0x40 ; // binary representation for i: 0100 0000 
j >> = 1 ; 

i >> = 1 ; 

// Q i and j is equal to the number of ?

i right after binary representation: 11000000 (to the right for right sign bit is negative, the high bit of 1), so that i = -64

J right after binary representation: 0010 0000 (shift right sign bit is positive for right, high bit 0), so that i = 32

(3)

char i = - 3 ; // binary representation: 1111 1101     

// i << 1 is the number? i >> 1 How much?

i << binary 1 is represented by: 11111010 (left logical shift left is discarded high, 0 low complement), interpreted as a signed char Number: -6

i >> binary 1 is represented as follows: 1111 1110 (right arithmetic shift right, high bit to 1 for negative), there is interpreted as a signed number char: 2

Left Right Summary:

It relates discarded left right, up, or up 1 0, but this ultimately interpreted as a string of binary values ​​by defining what tags (if unsigned) determined.

Always left logical shift left, disposable high, 0 low fill;

Right arithmetic shift right, for signed numbers: positive high bit right shift 0, a negative high bit right shift. For unsigned: Logical shift right (i.e., the high bit of 0, the low discarded);

in conclusion:

So the question at the beginning is: whether there is a need and then on (&) 0x000000FF will completely clear the high data?

I think it is still necessary, because it does not know whether the type of the value is unsigned (unsigned), if the original 32-bit number is a common type int and is binary (1000 0000 ...... 0000 0000), then take the high 8 bit when the binary representation (...... 1111 1111 1000 0000), then the number will be very large and interpret it wrong. If it is unsigned, then fairly normal.

Therefore, in order to avoid future custom error led to the wrong type, or the subsequent displacement and the binary high (&) 0, the high completely cleared as well.

Guess you like

Origin www.cnblogs.com/jialin0x7c9/p/12158680.html