Logical Right Shift on negative integers in C?

限于喜欢 提交于 2021-02-05 02:39:45

问题


How does one go about doing a logical right shift of negative numbers in C? Basically I am looking for the C equivalent of >>> in java

i.e.

int one = -16711936 ;
        //int two = -16711936 ;
        //int three = -1;
        int r, g, b;
        System.out.println(Integer.toBinaryString(one));
         r = one << 8;
         r >>>= 24;

         g = one << 16;
         g >>>= 24;  //this always ends up being -1 in C, instead of 255

         b = one << 24;
         b >>>= 24;

回答1:


Cast the value to (unsigned int) before shifting.




回答2:


Unlike Java, C has unsigned integer types. You should always use unsigned integer types for bitwise manipulation like this. Unless you're an expert in C, doing it with signed types is going to lead you into the scary realm of undefined behavior where demons fly out of your nose.



来源:https://stackoverflow.com/questions/6239583/logical-right-shift-on-negative-integers-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!