Converting 24 bit integer (2s complement) to 32 bit integer in C++

前端 未结 2 1433
礼貌的吻别
礼貌的吻别 2021-01-15 15:37

The dataFile.bin is a binary file with 6-byte records. The first 3 bytes of each record contain the latitude and the last 3 bytes contain the longitude. E

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-15 15:58

    I am not understanding how I can store the CHAR "data" into an INT.

    Since char is a numeric type, there is no problem combining them into a single int.

    Since its receiving 24 integers of information stored into a BYTE

    It's 24 bits, not bytes, so there are only three integer values that need to be combined.

    An easier way of producing the same result without using conditionals is as follows:

    int interpret24bitAsInt32(byte[] byteArray) {     
        return (  
            (byteArray[0] << 24)
        |   (byteArray[1] << 16)
        |   (byteArray[2] << 8)
        ) >> 8;  
    }
    

    The idea is to store the three bytes supplied as an input into the upper three bytes of the four-byte int, and then shift it down by one byte. This way the program would sign-extend your number automatically, avoiding conditional execution.

    Note: This code is not portable, because it assumes 32-bit integer size. To make it portable use types:

    int32_t interpret24bitAsInt32(int8_t[] byteArray) {
        return (  
            (byteArray[0] << 24)
        |   (byteArray[1] << 16)
        |   (byteArray[2] << 8)
        ) >> 8; 
    }
    

    It also assumes that the most significant byte of the 24-bit number is stored in the initial element of byteArray, then comes the middle element, and finally the least significant byte.

提交回复
热议问题