Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical Right Shift on negative integers in C?

Tags:

c

bit

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;
like image 424
smooth_smoothie Avatar asked Jun 04 '11 21:06

smooth_smoothie


People also ask

Can we do right shift for negative numbers?

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.

Does C perform logical right shifts?

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.

Is >> in C arithmetic or logical?

When shifting an unsigned value, the >> operator in C is a logical shift. When shifting a signed value, the >> operator is an arithmetic shift.

How do you shift right logical?

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.


2 Answers

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.

like image 143
R.. GitHub STOP HELPING ICE Avatar answered Sep 30 '22 14:09

R.. GitHub STOP HELPING ICE


Cast the value to (unsigned int) before shifting.

like image 34
dan04 Avatar answered Sep 30 '22 13:09

dan04