What is the best way to convert an array of chars to bytes and vice versa?
Solution:
void CharToByte(char* chars, byte* bytes, unsigned int count){
There is no byte type in C++, and according to the Standard:
Edit:
1.7:
A byte is at least large enough to contain any member of the basic execution character set and is composed of a contiguous sequence of bits, the number of which is implementation-defined.
5.3.3:
sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1; the result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined.
There is no byte type in C++. You could typedef 'unsigned char' to 'byte' if that makes it nicer. Really thats all a byte is in C++ - an unsigned char. Aside from that, yes I would cast... but this cast is better:
unsigned_char_arr[i]= static_cast<unsigned char>(char_arr[i]);
or... just use the char array and cast it when it needs to be interpreted as an unsigned char...
In almost every C++ implementation you'll come across, a char
is exactly a an octet. This is not guaranteed by the C++ standard, but it's practically always the case. A byte
char
is always at least 8 bits large, and the exact number of bits is given by the preprocessor constant CHAR_BIT
. Also, the sizeof()
operator tells you the size of an object/type in terms of the number of char
s, not the number of bytes octets, so if you were on some weird system with a 16-bit char
and a 32-bit int
, then sizeof(int)
would be 2, not 4.
EDIT: Replaced byte by octet. A char
is guaranteed to be a byte by the C standard, but a byte is not guaranteed to be an octet, which is exactly 8 bits. If you've ever read any French technical literature, they always use 'octet' instead of 'byte', and they have kilooctets (KO), megaoctets (MO), etc. instead of kilbytes and megabytes.
The type char is one of the few types that has a size guaranteed by the ANSI standard and that size is 1 byte. As far as I know C does not directly define the type byte. However it would be just short of insane to have a type named byte which is not in fact a byte in size. Therefore a simple cast should do the trick.