Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将字节数组转换为相应整数的快速方法_Java_String_Integer_Bytearray - Fatal编程技术网

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”
,返回的
字节[]
如下:

我们看到的值是等值字符的ASCIIUnicode值。 有几种方法可以提取它们的等效字符,如
int
s:

  • 由于数字
    字符
    的排列,即“0”、“1”、“2”等是按所需的顺序(升序和顺序)进行的,因此我们可以通过对
    '0'
    即48的ASCII值进行子排序来提取字符
  • @Evgeniy Dorofev正确地指出了掩蔽方法:
  • “0”=>48=>11 0000

    我们注意到,如果我们提取最后4位,就会得到所需的
    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()通过随机访问文件接收的。