Search code examples
carraysserializationintbyte

Convert Bytes to Int / uint in C


I have a unsigned char array[248]; filled with bytes. Like 2F AF FF 00 EB AB CD EF ..... This Array is my Byte Stream which I store my Data from the UART (RS232) as a Buffer.

Now I want to convert the bytes back to my uint16's and int32's.

In C# I used the BitConverter Class to do this. e.g:

byte[] Array = { 0A, AB, CD, 25 };
int myint1 = BitConverter.ToInt32(bytes, 0);
int myint2 = BitConverter.ToInt32(bytes, 4);
int myint3 = BitConverter.ToInt32(bytes, 8);
int myint4 = BitConverter.ToInt32(bytes, 12);
//...
enter code here
Console.WriteLine("int: {0}", myint1); //output Data...

Is there a similiar Function in C ? (no .net , I use the KEIL compiler because code is running on a microcontroller)

With Regards Sam


Solution

  • Yes there is. Assume your bytes are in:

    uint8_t bytes[N] = { /* whatever */ };
    

    We know that, a 16 bit integer is just two 8 bit integers concatenated, i.e. one has a multiple of 256 or alternatively is shifted by 8:

    uint16_t sixteen[N/2];
    
    for (i = 0; i < N; i += 2)
        sixteen[i/2] = bytes[i] | (uint16_t)bytes[i+1] << 8;
                 // assuming you have read your bytes little-endian
    

    Similarly for 32 bits:

    uint32_t thirty_two[N/4];
    
    for (i = 0; i < N; i += 4)
        thirty_two[i/4] = bytes[i] | (uint32_t)bytes[i+1] << 8
            | (uint32_t)bytes[i+2] << 16 | (uint32_t)bytes[i+3] << 24;
                 // same assumption
    

    If the bytes are read big-endian, of course you reverse the order:

    bytes[i+1] | (uint16_t)bytes[i] << 8
    

    and

    bytes[i+3] | (uint32_t)bytes[i+2] << 8
        | (uint32_t)bytes[i+1] << 16 | (uint32_t)bytes[i] << 24
    

    Note that there's a difference between the endian-ness in the stored integer and the endian-ness of the running architecture. The endian-ness referred to in this answer is of the stored integer, i.e., the contents of bytes. The solutions are independent of the endian-ness of the running architecture since endian-ness is taken care of when shifting.