Interpret unsigned as signed

I am working on an embedded platform (ARM) and should be careful when working with bit patterns. Let it pretend that this line is beyond my influence:

uint8_t foo = 0xCE; // 0b11001110 

Interpreted as unsigned, it will be 206. But actually it was signed, thus resembling -50 . How can I continue to use this value as signed?

 int8_t bar = foo; // doesn't work 

and do not (result in 0x10 or 0x00 for all input values)

 int8_t bar = static_cast<int8_t>(foo); int8_t bar = reinterpret_cast<int8_t&>(foo); 

I just want the bit to remain intact, i.e. (bar == 0xCE)

Conversely, I would be interested in how to get bit patterns representing negative numbers into unsigned variables without spoiling the bit pattern. I am using GCC.

+7
source share
5 answers

The following works great for me, as it should be , although, as the comments say, this is determined by the implementation:

 int x = (signed char)(foo); 

In C ++, you can also say:

 int x = static_cast<signed char>(foo); 

Note that promotion always tries to keep the value before re-interpreting bit patterns. Thus, you first need to give the signed type the same size as your unsigned type in order to force the signed reinterpretation.

(I usually encounter the opposite problem when trying to print char as pairs of hexadecimal digits.)

+8
source
 uint8_t foo = 0xCE; // 0b11001110 int8_t bar; memcpy( &bar, &foo, 1 ); 

It even has the added bonus that 99% of compilers fully optimize memcpy ...

+4
source

Something ugly along the lines of this?

 int8_t bar = (foo > 127) ? ((int)foo - 256) : foo; 

Does not rely on a conversion whose behavior is undefined.

+3
source

With the likelihood of GCC that unsigned values ​​are two additions, even on an embedded platform.

Then the 8-bit number 0xCE represents 0xCE-256 .

Since the two additions are really just modulo 2 n where n is the number of bits in the view.

EDIT : hm, for my sake it is better to give a concrete example:

 int8_t toInt8( uint8_t x ) { return (x >= 128? x - 256 : x); } 

EDIT 2 : I have not seen the final question of how to get a bit pattern into an unsigned variable. It is very simple: just assign. The result is guaranteed by the C ++ standard, namely, that the stored value is congruent (in time equal to one) equal to the destination, modulo 2 n .

Cheers and hth.,

0
source

You can access the value representation using a pointer. By reinterpreting the type of pointer, not the type of value, you should be able to replicate the view.

 uint8_t foo = 0xCE; int8_t bar = *reinterpret_cast<int8_t*>(&foo); 
0
source

All Articles