Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw data (bytes) and signed/unsigned variables

I've been told that whenever you work with bytes, you should declare your variables as unsigned chars. In Windows' data types, BYTE is declared as an unsigned char.

My questions:

Why?

Unsigned is a representation of integers from 0 to 255 and signed 128 to -127.

If that's the case, then how is EOF in binaries (-1) caught?

EOF is declared in stdio.h as a -1 #define macro.

like image 312
Andy Carter Avatar asked Apr 15 '26 14:04

Andy Carter


2 Answers

When you read chars from a stream, the return type of functions like std::getc is int, and not char. The constant EOF is of type int, and not char or unsigned char.

Even in the C++ I/O API, the I/O streams like std::ifstream deal with types char_type (that is the type of characters in the stream), and int_type that is a type that can hold all values of char_type, plus EOF.

like image 189
lrineau Avatar answered Apr 17 '26 05:04

lrineau


EOF is a status information, and is distinct from the data. However some functions have habit of using single return type for both. Example:

/* Return next data byte (0 - 255) or EOF (-1) if there was an error */
int readByte(...);

Point is that you need to have larger type than plain byte to be able to do this.

like image 43
user694733 Avatar answered Apr 17 '26 06:04

user694733



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!