Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uint8_t vs unsigned char

Tags:

c

typedef

What is the advantage of using uint8_t over unsigned char in C?

I know that on almost every system uint8_t is just a typedef for unsigned char, so why use it?

like image 522
Lyndon White Avatar asked Nov 12 '09 22:11

Lyndon White


People also ask

Is uint8_t same as unsigned char?

uint8_t always matches range and size of unsigned char and padding (none) when unsigned char is 8-bit. When unsigned char is not 8-bit, uint8_t does not exist.

Is uint8_t always unsigned char?

If it exists, uint8_t must always have the same width as unsigned char . However, it need not be the same type; it may be a distinct extended integer type. It also need not have the same representation as unsigned char ; for instance, the bits could be interpreted in the opposite order.

Should I use char or uint8_t?

If the intended use of the variable is to hold an unsigned numerical value, use uint8_t; If the intended use of the variable is to hold a signed numerical value, use int8_t; If the intended use of the variable is to hold a printable character, use char.

Is uint8_t signed?

2.2. A UINT8 is an 8-bit unsigned integer (range: 0 through 255 decimal).


2 Answers

It documents your intent - you will be storing small numbers, rather than a character.

Also it looks nicer if you're using other typedefs such as uint16_t or int32_t.

like image 78
Mark Ransom Avatar answered Sep 21 '22 15:09

Mark Ransom


Just to be pedantic, some systems may not have an 8 bit type. According to Wikipedia:

An implementation is required to define exact-width integer types for N = 8, 16, 32, or 64 if and only if it has any type that meets the requirements. It is not required to define them for any other N, even if it supports the appropriate types.

So uint8_t isn't guaranteed to exist, though it will for all platforms where 8 bits = 1 byte. Some embedded platforms may be different, but that's getting very rare. Some systems may define char types to be 16 bits, in which case there probably won't be an 8-bit type of any kind.

Other than that (minor) issue, @Mark Ransom's answer is the best in my opinion. Use the one that most clearly shows what you're using the data for.

Also, I'm assuming you meant uint8_t (the standard typedef from C99 provided in the stdint.h header) rather than uint_8 (not part of any standard).

like image 42
Chris Lutz Avatar answered Sep 18 '22 15:09

Chris Lutz