I would like to convert an int to a byte in C.
In Java, I'd write:
int num = 167;
byte b = num.toByte(); // -89
In C:
int num = 167;
???
byte
is a java signed integer type with a range of -128
to 127
.
The corresponding type in C is int8_t
defined in <stdint.h>
for architectures with 8-bit bytes. It is an alias for signed char
.
You can write:
#include <stdint.h>
void f() {
int num = 167;
int8_t b = num; // or signed char b = num;
...
If your compiler emits a warning about the implicit conversion to a smaller type, you can add an explicit cast:
int8_t b = (int8_t)num; // or signed char b = (signed char)num;
Note however that it is much more common to think of 8-bit bytes as unsigned quantities in the range 0
to 255
, for which one would use type uint8_t
or unsigned char
. The reason java byte
is a signed type might be that there is no unsigned type in this language, but it is quite confusing for non-native readers.
byte
can also be defined as a typedef:
typedef unsigned char byte; // 0-255;
or
typedef signed char byte; // -128-127;
Do not use type char
because it is implementation defined whether this type is signed or unsigned by default. Reserve type char
for the characters in C strings, although many functions actually consider these to be unsigned: strcmp()
, functions from <ctype.h>
...