简体   繁体   English

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

[英]Converting byte array to big integer: why does it have so many “f” hex values in the array output?

I'm trying to compare the BigInteger version of my digest with the actual digest bytes to see if any data was lost in the BigInteger conversion. 我正在尝试将摘要的BigInteger版本与实际摘要字节进行比较,以查看BigInteger转换中是否丢失了任何数据。 I found that it has all the same hex values in the output, except the byte array output has a lot of f 's in it, but the BigInteger output does not. 我发现它在输出中具有所有相同的十六进制值,除了字节数组输出中包含很多f ,而BigInteger输出却没有。 Why is that? 这是为什么?

Console Output 控制台输出

a7b7e9592daa0896db0517bf8ad53e56b1246923

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

Code

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();
        }
    }
}

Bytes are signed, so they're sign-extended when converted to int (for Integer.toHexString). 字节是带符号的,因此在转换为int时将对它们进行符号扩展(对于Integer.toHexString)。 Thus any negative byte will become a negative integer, which has high-order bits 1 (two's complement). 因此,任何负字节将变为负整数,其具有高阶位1(二进制补码)。 Use 采用

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

to mask out the sign-extended bits, leaving only the bottom 8 bits. 屏蔽掉符号扩展位,只保留低8位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM