Jacko
Jacko

Reputation: 13195

Bit twiddling to get sign bit of 32 bit int

I would like to convert

(n < 0 ? 1 : 0)

into bit twiddling (assuming 2s complement arch).

for performance reasons.

Upvotes: 1

Views: 104

Answers (1)

user555045
user555045

Reputation: 64904

With an unsigned shift,

x = n >>> 31; // Java's unsigned shift

x = (int)((uint)n >> 31); // C#'s unsigned shift, the casts are effectively nop

GCC does this automatically, other compilers may also. Or not. Your mileage may vary.

Upvotes: 3

Related Questions