Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte to signed int in C

I have a binary value stored in a char in C, I want transform this byte into signed int in C. Currently I have something like this:

char a = 0xff;
int b = a; 
printf("value of b: %d\n", b);

The result in standard output will be "255", the desired output is "-1".

like image 819
xwgou Avatar asked Dec 27 '22 20:12

xwgou


2 Answers

According to the C99 standard,

6.3.1.3 Signed and unsigned integers

When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.


You need to cast your char to a signed char before assigning to int, as any value char could take is directly representable as an int.

#include <stdio.h>

int main(void) {
  char a = 0xff;
  int b = (signed char) a;
  printf("value of b: %d\n", b);
  return 0;
}

Quickly testing shows it works here:

C:\dev\scrap>gcc -std=c99 -oprint-b print-b.c

C:\dev\scrap>print-b
value of b: -1

Be wary that char is undefined by the C99 standard as to whether it is treated signed or unsigned.

6.2.5 Types

An object declared as type char is large enough to store any member of the basic execution character set. If a member of the basic execution character set is stored in a char object, its value is guaranteed to be positive. If any other character is stored in a char object, the resulting value is implementation-defined but shall be within the range of values that can be represented in that type.

...

The three types char, signed char, and unsigned char are collectively called the character types. The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char.

like image 100
obataku Avatar answered Dec 29 '22 08:12

obataku


Replace:

char a = 0xff

by

signed char a = 0xff;  // or more explicit: = -1

to have printf prints -1.

If you don't want to change the type of a, as @veer added in the comments you can simply cast a to (signed char) before assigning its value to b.

Note that in both cases, this integer conversion is implementation-defined but this is the commonly seen implementation-defined behavior.

like image 39
ouah Avatar answered Dec 29 '22 09:12

ouah