0

I'm looking to convert this exact function from whatever language (Java I think) it is in to C#.

String hex_chr = "0123456789abcdef";
private String numToHex(int num) {
    String str = "";
    for (int j = 0; j <= 3; j++) {
        str += "" + hex_chr.charAt((num >> (j * 8 + 4)) & 15) + "" + hex_chr.charAt((num >> (j * 8)) & 15);
    }
    return str;
}
4

2 回答 2

4

If you were looking for an exact translation, you just need to deal with it as a char array. You can either use the ToCharArray() method or just index into the string directly.

String hex_chr = "0123456789abcdef";
private String numToHex(int num)
{
    String str = "";
    for (int j = 0; j <= 3; j++)
    {
        str += "" + hex_chr[(num >> (j * 8 + 4)) & 15] + "" + hex_chr[(num >> (j * 8)) & 15];
    }
    return str;
}

You may want to just use the .ToString("X") call that HighCore suggested, but keep in mind that this does not include the trailing zeroes present in the string that your code produces.

Likewise, to do that easier in Java the code should have just called Integer.toHexString().

于 2013-10-25T23:13:17.517 回答
1

The .Net Framework has a built-in function for that, there's no need to have that ugly, unmaintainable code in your project.

This example leverages a C# feature called Extension Methods

public static class IntExtensions
{
    public static string ToHex(this int value)
    {
       return value.ToString("X");
    }
}

Usage:

var myinteger = 10;
Console.WriteLine(myinteger.ToHex()); //Outputs "A"

-- or --

Console.WriteLine(255.ToHex()); //Outputs "FF"
于 2013-10-25T22:45:56.243 回答