2014-09-20 73 views
0

我试图将我的摘要的BigInteger版本与实际摘要字节进行比较,以查看是否有任何数据在BigInteger转换中丢失。我发现它在输出中具有所有相同的十六进制值,除了字节数组输出中有很多f's,但BigInteger输出没有。这是为什么?将字节数组转换为大整数:为什么数组输出中有很多“f”十六进制值?

控制台输出

a7b7e9592daa0896db0517bf8ad53e56b1246923 

ffffffa7 
ffffffb7 
ffffffe9 
59 
2d 
ffffffaa 
8 
ffffff96 
ffffffdb 
5 
17 
ffffffbf 
ffffff8a 
ffffffd5 
3e 
56 
ffffffb1 
24 
69 
23 

代码

import java.math.BigInteger; 
import java.nio.ByteBuffer; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 
import java.util.Arrays; 

public class Project2 
{ 
    public static void main(String[] args) 
    { 
     try 
     { 
      ByteBuffer buffer = ByteBuffer.allocate(4); 
      buffer.putInt(0xAABBCCDD); //Test value 
      byte[] digest = MessageDigest.getInstance("SHA-1").digest(buffer.array()); 
      BigInteger bi = new BigInteger(1, digest); 

      //Big Integer output: 
      System.out.println(bi.toString(16)); 
      System.out.println(""); 

      //Byte array output: 
      for(byte b : digest) 
      { 
       System.out.println(Integer.toHexString(b)); 
      } 
     } 
     catch (NoSuchAlgorithmException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
} 

回答

0

字节进行签名,所以他们符号扩展时转换为int(用于Integer.toHexString)。因此,任何负数字节将成为负整数,其高位为1(二进制补码)。使用

System.out.println(Integer.toHexString(b & 0xFF)); 

来掩盖符号扩展位,只留下底部8位。

+0

从Java 8开始,使用Integer.toHexString(Byte.toUnsignedInt(byte b))。 – greybeard 2016-02-13 10:40:50