Java 将字节数组转换为大整数:为什么数组输出中有这么多“f”十六进制值?

Java 将字节数组转换为大整数:为什么数组输出中有这么多“f”十六进制值?,java,Java,我试图将我的摘要的BigInteger版本与实际摘要字节进行比较,以查看在BigInteger转换过程中是否丢失了任何数据。我发现它在输出中有所有相同的十六进制值,除了字节数组输出中有很多f,但BigInteger输出中没有。为什么呢 控制台输出 代码 字节是有符号的,所以当Integer.toHexString转换为int时,字节是符号扩展的。因此,任何负字节都将成为一个负整数,具有高阶位1和2的补码。使用 System.out.println(Integer.toHexString(b &a

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

控制台输出

代码


字节是有符号的,所以当Integer.toHexString转换为int时,字节是符号扩展的。因此,任何负字节都将成为一个负整数,具有高阶位1和2的补码。使用

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

要屏蔽符号扩展位,只保留底部8位。

在Java 8中,使用Integer.tohextringbyte.toUnsignedIntbyte b。
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();
        }
    }
}
System.out.println(Integer.toHexString(b & 0xFF));