A char
is exactly one byte (per definition of the C standard). Unless bytes aren't exactly 8 bits on your system (such systems exist, but I bet you've never used or even seen one), uint8_t
and char
are exactly the same data type.
char c = 5;
uint8_t u = c;
And if you can do something like that with a data type, then you can just cast pointers as you wish between these two data types:
char c[] = { 'H', 'e', 'l', 'l', 'o' };
uint8_t * u = (uint8_t *)c;
uint8_t x = u[1];
// x is 101, which is the ASCII char code of 'e'
Actually you can even do that with strings, as a string is also just an array of characters, just one that is NUL
terminated.
char * c = "Hello";
// "Hello" is in fact just { 'H', 'e', 'l', 'l', 'o', '\0' }
uint8_t * u = (uint8_t *)c;
uint8_t x = u[1];
// x is 101, which is the ASCII char code of 'e'
The only thing you need to be careful is that the C standard does not define if char
is signed or unsigned. Unlike integer types that are signed by default and only unsigned if you request so (long
vs unsigned long
for example), a char
may be signed or unsigned by default. So if you need either one, you must use signed char
or unsigned char
as a data type. In practice that plays no role unless you perform certain math or logic operations on char
values (which you probably shouldn't do in modern C code to begin with).
And since there is no way that your message can be bigger than 256 characters (as otherwise the length would not fit into uint8_t
) and the length is always exactly one byte, I'd write the code as follows:
uint8_t messageLength = 0;
ssize_t bytesRead = recv(clients_sd, &messageLength, 1, 0);
if (bytesRead == -1) {
// Handle read error
}
if (bytesRead == 0) {
// Handle end of stream
}
char message[256];
bytesRead = recv(clients_sd, message, messageLength, 0);
if (bytesRead == -1) {
// Handle read error
}
if (bytesRead == 0) {
// Handle end of stream
}
if (bytesRead < messageLength) {
// Handle truncated message (message too small)
}
And once more, as apparently some people fail to understand my second sentence already: Everything I wrote above it under the assumption, that bytes on your system are 8 bits long. This code is not portable to platforms where bytes have more or less than 8 bits, that's already what my second sentence clearly points out, but that doesn't make my reply wrong. If it wasn't allowed to write C code that is not portable to all existing platforms on earth, 90% of all existing C code would be forbidden. You know the platform you are working with and you know the platforms you are targeting with your app, so it's your responsibility to make sure the code is correct for all these platforms.