符号付き10進数を32ビットのリトルエンディアンの2進数値に変換する必要があります。万が一、これを実行できる組み込みのJavaクラスまたは関数を知っている人はいますか?またはこれを行うために1つを構築しましたか?
データは-78.3829のような経度/緯度の値です。助けてくれてありがとう。
それがまったく役立つ場合は、longsをバイナリ文字列に変換し、バイナリ文字列を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;
}
}
10進値は使用しませんが、多少のガイダンスが得られる可能性があります。
バイナリレベルでエンディアンが何を意味するかがわかれば、変換は簡単です。問題は、それで本当に何をしたいのかということです。
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);
(ビッグエンディアンの場合は、行を下から上に並べるだけです...)