How to perform unsigned to signed conversion in Java?

前端 未结 2 1137
盖世英雄少女心
盖世英雄少女心 2021-01-02 22:10

Say I read these bytes: \"6F D4 06 40\" from an input device. The number is a longitude reading in MilliArcSeconds format. The top bit (0x80000000) is basically always zero

2条回答
  •  半阙折子戏
    2021-01-02 23:04

    Reading an unsigned integer as signed is a matter of identifying whether the most significant bit (negative flag) is set, and if so, flip all bits of the number (thus clearing the most significant bit, and switching the number to its negative representation. When performing the aforementioned process you must also make note of the fact that the resultant number is a negative.

    // Convert the hex bytes to an unsigned integer
    long MAS = Integer.ValueOf("6F D4 06 40".replace (" ",""),16);
    boolean isLongitudeNegative = false;
    
    // Is the negative-bit set? If so, strip it and toggle all bits.
    if (MAS & 0x40000000 > 0) {
        // then it's negative, so strip the negative bit and flip all the other bits
        MAS ^= 0xFFFFFFFF;
        // Throw away the unused bit.
        MAS &= 0x7FFFFFFF;
        isLongitudeNegative = true;
    }
    
    // Now convert from MAS to degrees minutes seconds
    String DMS = convertMASToDMS(isLongitudeNegative,MAS);
    

提交回复
热议问题