Reputation: 4168
I need this line of Java code:
Integer.toString(256 + (0xFF & arrayOfByte[i]), 16).substring(1)
converted to C# since I'm not sure how to work with "0xFF".
EDIT This is the full code:
MessageDigest localMessageDigest = MessageDigest.getInstance("SHA-256");
localMessageDigest.update(String.format(Locale.US, "%s:%s", new Object[] { paramString1, paramString2 }).getBytes());
byte[] arrayOfByte = localMessageDigest.digest();
StringBuffer localStringBuffer = new StringBuffer();
for (int i = 0; ; i++)
{
if (i >= arrayOfByte.length)
return localStringBuffer.toString();
localStringBuffer.append(Integer.toString(256 + (0xFF & arrayOfByte[i]), 16).substring(1));
}
Upvotes: 0
Views: 1241
Reputation: 719336
That Java expression is converting a signed byte to unsigned and then to hexadecimal with zero fill.
You should be able to code that in C#.
FWIW, the Java code gives the same answer as this:
Integer.toString(256 + arrayOfByte[i], 16).substring(1)
or
String.format("%02x", arrayOfByte[i])
Here's how the original works. The subexpression
(0xFF & arrayOfByte[i])
is equivalent to
(0xFF & ((int) arrayOfByte[i]))
which converts a signed byte (-128 to +127) to an unsigned byte (0 to +255). The purpose of the magic 256 +
in the original is to ensure that the result of toString
will be 3 hex digits long. Finally, the leading digit is removed, leaving you with a zero padded 2 digit hex number.
Upvotes: 1
Reputation: 1431
On that note, the actual way you can do this in C# is as follows.
String.Format("{0:x2}", arrayOfByte[i]);
Which is very similar to the Java
String.format("%02x", arrayOfByte[i]);
Which is a simpler way to do what they are doing above.
Upvotes: 7