Convert this line of Java code to C# code

老子叫甜甜 提交于 2021-01-21 06:15:41

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17635617/convert-this-line-of-java-code-to-c-sharp-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!