Convert array of char[] to byte[] and vice versa? C++


Question

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){
    for(unsigned int i = 0; i < count; i++)
        bytes[i] = (byte)chars[i];
}

void ByteToChar(byte* bytes, char* chars, unsigned int count){
    for(unsigned int i = 0; i < count; i++)
         chars[i] = (char)bytes[i];
}
1
13
5/18/2009 4:18:02 AM

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.

13
5/18/2009 4:40:53 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon