如何将带符号的十进制值转换为32位的little-endian二进制字符串?

时间:2012-08-03 16:09:04

标签: java binary

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

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

2 个答案:

答案 0 :(得分:2)

如果它有所帮助,这里有一个我将long转换为二进制字符串和二进制字符串转换为longs的类:

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;
    }

}

它不需要十进制值,但它可能会给你一些指导。

答案 1 :(得分:0)

一旦你知道endianess在二进制级别意味着什么,转换是微不足道的。问题是你真的想用它做什么?

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中的字节以在little / big endian顺序之间切换(转换是syme​​tric)。现在你有一个小的endian 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);

(对于big endian,你只需要从下到上排序......)