问题
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