2014-09-20 72 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