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;
Right Shifts For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used. The result of a right-shift of a signed negative number is implementation-dependent.
Most C and C++ implementations, and Go, choose which right shift to perform depending on the type of integer being shifted: signed integers are shifted using the arithmetic shift, and unsigned integers are shifted using the logical shift.
When shifting an unsigned value, the >> operator in C is a logical shift. When shifting a signed value, the >> operator is an arithmetic shift.
Logical Right Shifts When shifting right with a logical right shift, the least-significant bit is lost and a 0 is inserted on the other end. For positive numbers, a single logical right shift divides a number by 2, throwing out any remainders.
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.
Cast the value to (unsigned int)
before shifting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With