字节数组可变长度到数字
我需要将数字转换为字节数组,然后返回数字。 问题是字节数组的大小是可变的,所以我需要将数字转换给他的字节长度,我想出了一个方法为:(JAVA)字节数组可变长度到数字
private static byte[] toArray(long value, int bytes) {
byte[] res = new byte[bytes];
final int max = bytes*8;
for(int i = 1; i <= bytes; i++)
res[i - 1] = (byte) (value >> (max - 8 * i));
return res;
}
private static long toLong(byte[] value) {
long res = 0;
for (byte b : value)
res = (res << 8) | (b & 0xff);
return res;
}
这里我用一个长因为8是我们可以使用的最大字节数。 这种方法与正数完美结合,但我似乎无法使解码工作与否定。
编辑:测试这个我已经与处理所述值Integer.MIN_VALUE的+ 1(-2147483647)和4个字节试图
接受此作为工作溶液后,将Asker进一步优化了 。
我已经包括自己下面linked code
为 参考:
private static long toLong(byte[] value) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
final byte val = (byte) (value[0] < 0 ? 0xFF : 0);
for(int i = value.length; i < Long.BYTES; i++)
buffer.put(val);
buffer.put(value);
return buffer.getLong(0);
}
早前出现过
编辑:基于评论(认识问题更好)
要让你的toLong
功能同时处理负 & 积极数试试这个:
private static long toLong(byte[] value)
{
long res = 0;
int tempInt = 0;
String tempStr = ""; //holds temp string Hex values
tempStr = bytesToHex(value);
if (value[0] < 0)
{
tempInt = value.length;
for (int i=tempInt; i<8; i++) { tempStr = ("FF" + tempStr); }
res = Long.parseUnsignedLong(tempStr, 16);
}
else { res = Long.parseLong(tempStr, 16); }
return res;
}
下面是相关bytesToHex
功能(重新分解与任何byte[]
输入出的现成工作...)
public static String bytesToHex(byte[] bytes)
{ String tempStr = ""; tempStr = DatatypeConverter.printHexBinary(bytes); return tempStr; }
这不是可变的,我不能说“把这个数字放在5个字节中”或者“从这5个字节中得到我的号码” – SnowyCoder
你不应该只输入5个字节。所有语言/操作系统一次读取1,2,4或8个字节。如果您的电话号码只需要5个字节,那么您已经处于实际必须读取8个字节的状态。使用[** bit-shifting **](http://stackoverflow.com/a/141873/2057709)将您的40位(5个字节)保留在Array的一侧,并用零位填充剩余的3个字节的时隙。 –
我已经做了类似的事情(请参阅我的问题),但问题是我不知道如何处理负值 – SnowyCoder
刚刚测试过它: – SnowyCoder
'long v = Integer.MIN_VALUE + 1; byte [] res = new byte [4]; longToByteArray(v,0,res,0,4); long out = byteArrayToLong(res,0,0L,0,4); System.out.println(out);'否定性丢失 – SnowyCoder
@SnowyCoder如果这个答案有效,那么使用'✓'图标标记为解决方案。 –
不知道如果你的问题现在已经解决了,但...看看我的答案是否可以帮助你处理l arge负值。 –