0

我需要将带符号的十进制数转换为 32 位 little-endian 二进制值。有没有人知道可以做到这一点的内置 Java 类或函数?或者已经建造了一个来做到这一点?

数据是经度/纬度值,例如 -78.3829。谢谢你的帮助。

4

2 回答 2

2

如果它有帮助,这是我制作的一个类,它将长整数转换为二进制字符串,将二进制字符串转换为长整数:

public class toBinary {

    public static void main(String[] args) {
        System.out.println(decimalToBinary(16317));
        System.out.println(binaryToDecimal("11111111111111111111111111111111111100101001"));
    }

    public static long binaryToDecimal(String bin) {
        long result = 0;
        int len = bin.length();
        for(int i = 0; i < len; i++) {
            result += Integer.parseInt(bin.charAt(i) +  "") * Math.pow(2, len - i - 1);
        }
        return result;
    }

    public static String decimalToBinary(long num) {
        String result = "";
        while(true) {
            result += num % 2;
            if(num < 2)
                break;
            num = num / 2;
        }
        for(int i = result.length(); i < 32; i++)
            result += "0";
        result = reverse(result);
        result = toLittleEndian(result);
        return result;
    }

    public static String toLittleEndian(String str) {
        String result = "";
        result += str.substring(24);
        result += str.substring(16, 24);
        result += str.substring(8, 16);
        result += str.substring(0, 8);
        return result;
    }

    public static String reverse(String str) {
        String result = "";
        for(int i = str.length() - 1; i >= 0; i--)
            result += str.charAt(i);
        return result;
    }

}

它不采用十进制值,但它可能会给您一些指导。

于 2012-08-03T16:20:25.353 回答
0

一旦您知道字节序在二进制级别上的含义,转换就很简单了。问题更多的是你真的想用它做什么?

public static int flipEndianess(int i) {
    return (i >>> 24)          | // shift byte 3 to byte 0
           ((i >> 8) & 0xFF00) | // shift byte 2 to byte 1
           (i << 24)           | // shift byte 0 to byte 3
           ((i & 0xFF00) << 8);  // shift byte 1 to byte 2
}

这个小方法将交换 int 中的字节以在小/大端顺序之间切换(转换是对称的)。现在你有一个小字节序 int。但是你会用 Java 做什么呢?

您更有可能需要将数据写入流或其他东西,那么它只是一个问题,您以什么顺序写出字节:

// write int to stream so bytes are little endian in the stream
// OutputStream out = ... 
out.write(i);
out.write(i >> 8);
out.write(i >> 16);
out.write(i >> 24);

(对于大端,您只需从下到上排列线条......)

于 2012-08-03T17:03:45.297 回答