简体   繁体   中英

Converting Java hash to C# and need help understanding the Java

I'm converting a Java library over to C# as I rewrite a legacy application and I need some assistance. I need to understand what this line in Java is doing:

sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1,3))

and if this C# line is equivalent

result += (Convert.ToInt32(b).ToString("x2") + " ").Substring(1,3);

In both cases b is a byte from a SHA-1 hash that the code is looping through. The Java part I don't understand is ((b & 0xFF) | 0x100). It looks like it's padding it?

Ordinarily I would compare the output from the Java application to what my C# is generating but I am not in a postition to do that right now (and it's frustrating me - trust me).

您无需彻底更改原始文件-C#等效项(假设“ sb”是StringBuilder)仅是:

sb.Append(((b & 0xFF) | 0x100).ToString("x").Substring(1, 2));

b & 0xFF will mask the lowest byte. So whatever b is, you will get something between 0x00 and 0xFF.

In the resulting integer, 9th bit is set, no matter what it was before. So you'll have something between 0x0100 to 0x01FF.

From that string the substring from index 1 to 3 is cropped. It will give you the last two digits which will be something between 00 and FF. The |0x100 is a neat trick to have Integer.toHexString give you a leading zero for the last two digits which it wouldn't according to it's javadoc ...

If I remeber correctly, your C# code does not exactly the same. But I hope with this explanation you can build it up yourself :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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