is defined behavior extract sign of 32 bit integer way:
#include <stdint.h> int get_sign(int32_t x) { return (x & 0x80000000) >> 31; }
do result of 0
or 1
?
no, incorrect because right shifting signed integer negative value implementation-defined, specified in c standard:
6.5.7 bitwise shift operators
the result of
e1 >> e2
e1
right-shiftede2
bit positions. ife1
has unsigned type or ife1
has signed type , nonnegative value, value of result integral part of quotient ofe1 / 2
e2
. ife1
has signed type , negative value, resulting value implementation-defined.
you should cast x
(uint32_t)
before masking , shifting.
edit: wrong answer! shall keep answer here example of looking, intuitive incorrect reasoning. explained in other answers, there not right shifting of negative value in code posted. type of x & 0x80000000
1 of signed integer or unsigned integer types depending on implementation characteristics, value positive, either 0
or 2147483648
. right shifting value not implementation-defined, result either 0
or 1
. whether result value of sign bit less obvious: value of sign bit except contorted corner cases, hybrid architectures quite unlikely exist , non standard conforming anyway.
Comments
Post a Comment