[英]Convert this line of Java code to C# code
I need this line of Java code: 我需要以下这行Java代码:
Integer.toString(256 + (0xFF & arrayOfByte[i]), 16).substring(1)
converted to C# since I'm not sure how to work with "0xFF". 转换为C#,因为我不确定如何使用“ 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));
}
On that note, the actual way you can do this in C# is as follows. 关于这一点,在C#中执行此操作的实际方法如下。
String.Format("{0:x2}", arrayOfByte[i]);
Which is very similar to the Java 与Java非常相似
String.format("%02x", arrayOfByte[i]);
Which is a simpler way to do what they are doing above. 这是执行上述操作的一种更简单的方法。
That Java expression is converting a signed byte to unsigned and then to hexadecimal with zero fill. 该Java表达式将带符号字节转换为无符号字节,然后转换为零填充的十六进制。
You should be able to code that in C#. 您应该能够使用C#进行编码。
FWIW, the Java code gives the same answer as this: FWIW,Java代码给出的答案与此相同:
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). 它将有符号字节(-128至+127)转换为无符号字节(0至+255)。 The purpose of the magic 256 +
in the original is to ensure that the result of toString
will be 3 hex digits long. 原始版本中的魔术256 +
的目的是确保toString
的结果为3个十六进制数字长。 Finally, the leading digit is removed, leaving you with a zero padded 2 digit hex number. 最后,删除了前导数字,为您提供了一个零填充的2位十六进制数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.