Unexpected bitrate results

I initialize an unsigned short int with a = 0xff (all bits are set). Then I assign b to → 7, which should give (0000 0001), and he does it. However, it is strange that when I assign c to <7, it is not equivalent (1000 0000). I tested this by outputting 0x80 (this is 1000 0000) and c, but they do not match.

Here is the code:

unsigned short int a = 0xff;
unsigned short int b = a>>7;
unsigned short int c = a<<7; // c should == 0x80

I am not sure what the problem is. Any help is appreciated. Thanks.

PS By "output" I mean output 0x80 and c in decimal and hexadecimal.

+3
source share
5 answers

the short int has 16, not just 8 bits.

, , , "0111 1111 1000 0000" 0xff < 7.

+9

, <stdint.h>


int "" 16 . , , 16, , - promises.

, , :

#include <stdint.h>

  int8_t  a;
 uint8_t  b;
 int16_t  x;
uint16_t  y;

, short. - Microsoft - C99 , <stdint.h>. , V++ stdint.

+6

, 0x7f80. , :

unsigned short int c = b <<7; // c should == 0x80

+2

, V++ ( C) inttypes.h, C99. (, Paul Hsieh stdint.h).

0

If you want to get this result, you can chop off a part a << 7larger than the 8th least significant bit using bitwise and:

unsigned short int c = (a << 7) & 0xff;
0
source

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


All Articles