Java 将字节数组转换为相应整数的快速方法
首先,这听起来像是这里的问题: 但是我的字节数组的起源是一个字符串,类似这样:Java 将字节数组转换为相应整数的快速方法,java,string,integer,bytearray,Java,String,Integer,Bytearray,首先,这听起来像是这里的问题: 但是我的字节数组的起源是一个字符串,类似这样: byte[] foo = new byte[8]; foo = "12345678".getBytes(); byte foo[] = "12345678".getBytes(); //Since it is an 'integer' essentially, it will contain ASCII values of decimal digits. long num = 0; //Store number
byte[] foo = new byte[8];
foo = "12345678".getBytes();
byte foo[] = "12345678".getBytes();
//Since it is an 'integer' essentially, it will contain ASCII values of decimal digits.
long num = 0; //Store number here.
for(int i = foo.length - 1; i >= 0; i--)
{
num = num * 10 + (foo[i] - '0'); // or (foo[i] - 48) or (foo[i] & 0xf)
}
有没有比Integer.parseInt(新字符串(foo))
?
字符串仅包含表示整数的数字。请尝试此操作
int res = 0;
for(int i = foo.length -1, m = 1; i >=0; i--, m *= 10) {
res += (foo[i] & 0xF) * m;
}
您可以尝试以下方法:
byte[] foo = new byte[8];
foo = "12345678".getBytes();
byte foo[] = "12345678".getBytes();
//Since it is an 'integer' essentially, it will contain ASCII values of decimal digits.
long num = 0; //Store number here.
for(int i = foo.length - 1; i >= 0; i--)
{
num = num * 10 + (foo[i] - '0'); // or (foo[i] - 48) or (foo[i] & 0xf)
}
num
存储所需的号码
注意事项:确保只使用十进制数字
编辑: 机制 调用
字符串的getBytes()
“12345678”
,返回的字节[]
如下:
我们看到的值是等值字符的ASCII或Unicode值。
有几种方法可以提取它们的等效字符,如int
s:
字符
的排列,即“0”、“1”、“2”等是按所需的顺序(升序和顺序)进行的,因此我们可以通过对'0'
即48的ASCII值进行子排序来提取字符int
。
要做到这一点,我们需要用以下方法提取它们。
让我们以foo[1]
为例,即50
50 & 0xf (original)
= 50 & 15 (in Decimal)
= 11 0010 & 1111 (in Binary)
= 0010 (result)
= 2 (Decimal)
因此,获得所需的数字。有必要以正确的方式将它添加到
num
int中(我希望每个程序员都对此有所了解)。您是否分析了您的代码并证明这是一个实际的(而不是感知的)瓶颈?保留字符串引用,并对其应用Integer.parseInt,将保存两个数组副本。不清楚为什么要使用字节数组而不是Integer.parseInt(originalString)
。。。顺便说一句,newbyte[8]
创建了一个数组,该数组会立即被丢弃……我使用的是字节数组,因为数据是使用read()通过随机访问文件接收的。