我想在我的 Android 应用程序中将长值转换为字节数组。当我在 C# 中转换它时,我的应用程序必须按照相同的结果将它转换为 byte[]!但在 android 中,我得到了大数的 (-) 数! 我在网上搜索这个问题并找到了很多方法来只将 long 转换为 byte[] 但从未发现任何关于这个问题的信息
长值:47063350
C# 值:
[0] 0 byte
[1] 0 byte
[2] 0 byte
[3] 0 byte
[4] 2 byte
[5] 206 byte
[6] 33 byte
[7] 54 byte
安卓值(value):
[0] = 0
[1] = 0
[2] = 0
[3] = 0
[4] = 2
[5] = -50
[6] = 33
[7] = 54
206 现在是 -50。
我的转换方法:
...
public static final int FLAG_JAVA = 0;
public static final int FLAG_REVERSE = -1;
...
public static byte[] getBytes(long i, int flag) {
byte[] b = new byte[8];
switch (flag) {
case BitConverter.FLAG_JAVA:
b[0] = (byte) ((i >> 56) & 0xff);
b[1] = (byte) ((i >> 48) & 0xff);
b[2] = (byte) ((i >> 40) & 0xff);
b[3] = (byte) ((i >> 32) & 0xff);
b[4] = (byte) ((i >> 24) & 0xff);
b[5] = (byte) ((i >> 16) & 0xff);
b[6] = (byte) ((i >> 8) & 0xff);
b[7] = (byte) ((i >> 0) & 0xff);
break;
case BitConverter.FLAG_REVERSE:
b[7] = (byte) ((i >> 56) & 0xff);
b[6] = (byte) ((i >> 48) & 0xff);
b[5] = (byte) ((i >> 40) & 0xff);
b[4] = (byte) ((i >> 32) & 0xff);
b[3] = (byte) ((i >> 24) & 0xff);
b[2] = (byte) ((i >> 16) & 0xff);
b[1] = (byte) ((i >> 8) & 0xff);
b[0] = (byte) ((i >> 0) & 0xff);
break;
default:
break;
}
return b;
}
最佳答案
我认为您在有符号字节和无符号字节之间遇到了问题
对于你的 android 值,你得到一个带符号的字节,它是 -50,所以如果你想让它无符号,这是一个解决方案:
public static byte signedToUnsigned(byte signed){
return signed & 0xff;
}
在 signedToUnsigned 之后,您将得到 206 而不是 -50。
关于c# - 在 C# 中通过相同的结果在 Android 中将 Long 转换为 Byte [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26084431/