Reading “integer” size bytes from a char* array.

前端 未结 9 1272
深忆病人
深忆病人 2020-12-09 05:13

I want to read sizeof(int) bytes from a char* array.

a) In what scenario\'s do we need to worry if endianness needs to be checked?

相关标签:
9条回答
  • 2020-12-09 05:38

    How about

    int int_from_bytes(const char * bytes, _Bool reverse)
    {
        if(!reverse)
            return *(int *)(void *)bytes;
    
        char tmp[sizeof(int)];
    
        for(size_t i = sizeof(tmp); i--; ++bytes)
            tmp[i] = *bytes;
    
        return *(int *)(void *)tmp;
    }
    

    You'd use it like this:

    int i = int_from_bytes(bytes, SYSTEM_ENDIANNESS != ARRAY_ENDIANNESS);
    

    If you're on a system where casting void * to int * may result in alignment conflicts, you can use

    int int_from_bytes(const char * bytes, _Bool reverse)
    {
        int tmp;
    
        if(reverse)
        {
            for(size_t i = sizeof(tmp); i--; ++bytes)
                ((char *)&tmp)[i] = *bytes;
        }
        else memcpy(&tmp, bytes, sizeof(tmp));
    
        return tmp;
    }
    
    0 讨论(0)
  • 2020-12-09 05:38

    You need to worry about endianess only if the data you're reading is composed of numbers which are larger than one byte.
    if you're reading sizeof(int) bytes and expect to interpret them as an int then endianess makes a difference. essentially endianness is the way in which a machine interprets a series of more than 1 bytes into a numerical value.

    0 讨论(0)
  • 2020-12-09 05:40

    Do you mean something like that?:

    char* a;
    int i;
    memcpy(&i, a, sizeof(i));
    

    You only have to worry about endianess if the source of the data is from a different platform, like a device.

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