6

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; 
2
  • 3
    Right shift in C is implementation defined, which means you don't know whether it's arithmetic or logical (though most of the time it's arithmetic). Which means that you have to do some additional manual bit bashing if you want a logical shift (or, well, casting). Commented Jun 4, 2011 at 21:50
  • One doesn't generally, because unlike Java you don't have to. Commented Jun 5, 2011 at 8:59

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was aware of that. However Java doesn't have unsigned types so I couldn't show that.
5

Cast the value to (unsigned int) before shifting.

1 Comment

Better yet, use unsigned types to begin with. Any use of signed types to pack values like this is dangerous, especially if the programmer is used to Java and does not know C's rules.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.