同一条语句中的按位左移和右移 [英] Bitwise shift left and right in the same statement

查看:92
本文介绍了同一条语句中的按位左移和右移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char c2=i1<<8>>24;是否有效的C语法? (i1是无符号整数),另外,它会产生分别将i1左移8位和右移24位的结果吗?我正在解压缩先前存储在i1中的char和其他三个char.下面的代码:

Is char c2=i1<<8>>24; valid C syntax? (Where i1 is and unsigned integer) Additionally, will it yield the result of shifting i1 8 bits left and 24 bits right respectively? I am unpacking a char previously stored in i1, along with three other chars. Code below:

unsigned char b3 = 202;
unsigned char b2 = 254;
unsigned char b1 = 186;
unsigned char b0 = 190;
...


unsigned int i1=202;
i1=i1<<8;
i1=i1+254;
i1=i1<<8;
i1=i1+186;
i1=i1<<8;
i1=i1+190;
...

char c1=i1>>24;
char c2=i1<<8>>24;

推荐答案

语法很好(尽管很难阅读),它将被解析为c2 = (i1 << 8) >> 24.

The syntax is fine (although hard to read) and it will be parsed as c2 = (i1 << 8) >> 24.

因此它将左移i1 8个位置,从而将最左边的8位偏移左边缘,然后将结果右移24个位置,从而将最右边的16位偏移右边缘.如果那是您想要的,那么您就很好.我会使用括号使其更具可读性.

So it will left shift i1 8 positions, thereby shifting the leftmost 8 bits off the lefthand edge, and then right shift the result 24 positions, thereby shifting the rightmost 16 bits off the righthand edge. If that's what you wanted, then you're good. I'd use parentheses to make it more readable.

如果只是要将其转换为char,那么为什么需要删除高阶位并不清楚(尽管确实存在某些架构,其中intchar大小相同.)

If you're just going to convert that to a char, it's not obvious why you feel the need to remove the high-order bits (although it is true that there may be architectures in which int and char are the same size.)

此外,正如约翰·博林格(John Bollinger)指出的那样,最终结果可能会大于char中的大小,在char是带符号类型的常见情况下,这没有得到很好的定义. (即使unsigned int是32位,也是如此,因为从技术上讲,您不能为8位带符号的字符分配大于127的值.)

Also, as noted by John Bollinger, it is possible for the end result to be larger than can fit in a char, which is not well defined in the common case that char is a signed type. (That will be true even if unsigned int is 32 bits, because you technically cannot assign a value greater than 127 to an 8-bit signed character.)

这篇关于同一条语句中的按位左移和右移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆