Convert Bytes to Int / uint in C

前端 未结 4 1719
不知归路
不知归路 2020-11-27 05:17

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

相关标签:
4条回答
  • 2020-11-27 05:32

    There's no standard function to do it for you in C. You'll have to assemble the bytes back into your 16- and 32-bit integers yourself. Be careful about endianness!

    Here's a simple little-endian example:

    extern uint8_t *bytes;
    uint32_t myInt1 = bytes[0] + (bytes[1] << 8) + (bytes[2] << 16) + (bytes[3] << 24);
    

    For a big-endian system, it's just the opposite order:

    uint32_t myInt1 = (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3];
    

    You might be able to get away with:

    uint32_t myInt1 = *(uint32_t *)bytes;
    

    If you're careful about alignment issues.

    0 讨论(0)
  • 2020-11-27 05:39

    In case of little-endian, can't you just use memcpy?

    memcpy((char*)&myint1, aesData.inputData[startindex], length);
    
    0 讨论(0)
  • 2020-11-27 05:47

    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.

    0 讨论(0)
  • 2020-11-27 05:48
                char letter = 'A';
                size_t filter = letter;
                filter = (filter <<  8 | filter);
                filter = (filter << 16 | filter);
                filter = (filter << 32 | filter);
                printf("filter: %#I64x \n", filter); 
    

    result: "filter: 0x4141414141414141"

    0 讨论(0)
提交回复
热议问题