C/C++ Check to see if bit 31 is set in an unsigned int -
i'm trying check , see if bit set in unsigned int. i'm not sure how can this, assume this. i'm trying make cdq instruction in c++ (but function)
here have
unsigned int cdq(unsigned int eax) { unsigned int edx = 0; if( (eax >> 31) & 1 ) { edx = 0xffffffff; } return edx }
when use function following values:
cdq(0x12345678) bit 31 set (1) should return (unsigned int)-1 cdq(0x01) bit 31 not set (0) should return 0
the problem returns 0, , i'm not sure why
cdq(0x12345678) bit 31 set (1)
no, it's not ... highest bit set bit 28:
1 2 3 4 5 6 7 8 0001 0010 0011 0100 0101 0110 0111 1000 ^ ^ | | 31 28
you code should work, use
if( eax & (1u << 31) ) edx = 0xffffffff;
since it's bit more direct , shifts constant rather variable less work @ run time (although optimizing compiler should produce same code both).
actually write like
int cdq(int eax) { return eax < 0? -1 : 0; }
by way, code doesn't implement cdq because eax , edx variables not hardware eax , edx registers. , it's not idea replicate asm instructions c functions anyway ... c has own features doing these sorts of things, e.g.,
int32_t foo = -0x12345678; int64_t bar = (int64_t)foo;
Comments
Post a Comment