Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right shift count >= width of type or left shift count >= width of type

Tags:

c

I am new to bits, I am trying to get 64 bit value send using UDP.

int plugin(unsigned char *Buffer) {
     static const uint8_t max_byte = 0xFF;
     uint8_t id[8];
     id[0] = (uint8_t)((Buffer[0]) & max_byte);
     id[1] = (uint8_t)((Buffer[1] >> 8)  & max_byte);
     id[2] = (uint8_t)((Buffer[2] >> 16) & max_byte);
     id[3] = (uint8_t)((Buffer[3] >> 24) & max_byte);
     id[4] = (uint8_t)((Buffer[4] >> 32) & max_byte);
     id[5] = (uint8_t)((Buffer[5] >> 40) & max_byte);
     id[6] = (uint8_t)((Buffer[6] >> 48) & max_byte);
     id[7] = (uint8_t)((Buffer[7] >> 56) & max_byte);

}

I am getting error right shift count >= width of type. I tried other way aswell

int plugin(unsigned char *Buffer) {
     uint64_t id = (Buffer[0] | Buffer[1] << 8 | Buffer[2] << 16 | Buffer[3] << 24 | Buffer[4] < 32 | Buffer[5] << 40 | Buffer[6] << 48 | Buffer[7] << 56);
     printf("ID %" PRIu64 "\n", id);
}

Its getting error left shift count >= width of type I checked the system it is x86_64. Could someone please tell me the reason why its happening? Please suggest me a way forward.

like image 656
Abu Avatar asked Sep 27 '16 09:09

Abu


1 Answers

This happens because of default integer promotion, basically.

When you do this:

uint64_t id = Buffer[7] << 56;

That Buffer[7] is an unsigned char, but it gets promoted to int in the arithmetic expression, and your int is not 64 bits. The type of the left hand side does not automatically "infect" the right hand side, that's just not how C works.

You need to cast:

const uint64_t id = ((uint64_t) Buffer[7]) << 56;

and so on.

like image 137
unwind Avatar answered Oct 20 '22 09:10

unwind