Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are characters signed or unsigned?

Tags:

c

char

What are the possible situations where would we need a signed char? I guess the only use of this is in conversion of a char quantity to an integer.

like image 840
Chankey Pathak Avatar asked Feb 24 '23 08:02

Chankey Pathak


2 Answers

char is an integer, usually with a width of 8 bits. But because its signedness is implementation defined (ie depends on compiler), it is probably not a good idea to use it for arithmetic. Use unsigned char or signed char instead, or if you want to enforce the width, use uint8_t and int8_t from stdint.h.

like image 38
Jens Gustedt Avatar answered Mar 02 '23 20:03

Jens Gustedt


If I remember right, a "char" may be signed or unsigned (it depends on the compiler/implementation). If you need an unsigned char you should explicitly ask for it (with "unsigned char") and if you need a signed char you should explicitly ask for it (with "signed char").

A "char" is just a (typically 8-bit) integer. It has nothing to do with characters.

A character could be anything, depending on what you're doing. I prefer using "uint32_t" and Unicode (UTF-32). For crusty old/broken software that uses ASCII, a char is fine (regardless of whether "char" is signed or unsigned). For UTF-8 you'd probably want to use "unsigned char" or "uint8_t".

You might also be tempted to try to use "wchar_t" (and the "wchar.h" header), but there's lots of ways that can go wrong (do some research if you're tempted).

like image 143
Brendan Avatar answered Mar 02 '23 20:03

Brendan