Reputation: 421
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;
???
Upvotes: 1
Views: 8767
Reputation: 144550
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>
...
Upvotes: 3
Reputation: 213319
In computer science, the term byte is well-defined as an 8 bit chunk of raw data. Apparently Java uses a different definition than computer science...
-89
is not the value 167
"converted to a byte". 167
already fits in a byte, so no conversion is necessary.
-89
is the value 167
converted to signed 2's complement with 8 bits representation.
The most correct type to use for signed 2's complement 8 bit integers in C is int8_t
from stdint.h
.
Converting from int
to int8_t
is done implicitly in C upon assignment. There is no need for a cast.
int num = 167;
int8_t b = num;
Upvotes: 3
Reputation: 8001
You can simply cast to a byte:
unsigned char b=(unsigned char)num;
Note that if num
is more than 255 or less than 0 C won't crash and simply give the wrong result.
Upvotes: 4
Reputation: 124
There is no such type as Byte in native C. Although if you don't want to import new libs, you can create one like this :
typedef unsigned char Byte
And then create any variable you'd like with it :
int bar = 15;
Byte foo = (Byte)bar
Upvotes: 3