I have an unsigned char with binary value 11010001.
If I were to convert it to unsigned integer its value would be 209. Its signed value however should be -81.
If I normally convert it to integer by type casting it gives me a value of 209, but I want the signed value of -81.
I understand that when I convert it to integer the first 1 or 3 bytes (depending 16 bit or 32 bit integer value) will be 0 and so the whole integer value will be considered positive.
How do I get the signed value from this unsigned char?
Asked
Active
Viewed 151 times
0

The Prenx
- 483
- 4
- 15
-
1http://stackoverflow.com/questions/8317295/convert-unsigned-int-to-signed-int-c – Marshall Tigerus Jun 14 '16 at 19:08
-
thanks for the response @MarshallTigerus but it does not help in my case as the difference is 3 bytes here between char and int. So even if I use a short int I get first 8 bits 0 i.e. a positive number. – The Prenx Jun 14 '16 at 19:13
-
4The signed value isn't `-81` it is `-47`. Try `printf("%d\n", (signed char)c);` – Weather Vane Jun 14 '16 at 19:15
-
1Convert it to signed char first: `int n = (int)(signed char)uc;`. Then you will get sign extension. – Aconcagua Jun 14 '16 at 19:16
-
@Dmitri And what about values < 128? – Aconcagua Jun 14 '16 at 19:19
-
Thanks for all your suggestions. I got it working by using int n = (int)(signed char)uc; Thanks @Aconcagua – The Prenx Jun 14 '16 at 19:20
-
According to 6.3.1.3.3 converting unsigned char to signed char is implementation defined. – user3528438 Jun 14 '16 at 19:20
-
But at least not undefined behaviour... So it's valid, but possibly not portable to everywhere. – Aconcagua Jun 14 '16 at 19:24
-
1@user3528438 that was a good (last-but-one) comment except it should be `y = x<=127 ? x : (x-256);` – Weather Vane Jun 14 '16 at 19:30
-
1This question is actually not a duplicate of the int case, because it's easier. In the int case you can not easily do `x-4294967296` because `4294967296` is not representable by a normal 32bit `int` and getting 64bit int involved is a waste of CPU resources for such a simple task. That's the only reason to use bit-hacking. For this one, doing (x-256) for x>127 is feasible because 256 is representable by int. – user3528438 Jun 14 '16 at 19:33
-
@WeatherVane You are right. I've removed my incorrect comment. – user3528438 Jun 14 '16 at 19:35
-
1@Aconcagua `int n = (signed char)uc;` would be sufficient. No need for `(int)`. – chux - Reinstate Monica Jun 14 '16 at 19:36
-
Not an exact duplicate of that question IMO... similar but there are differences (paticularly, the type) – M.M Jun 14 '16 at 22:29