Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

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

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 "
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...