0

I would like to convert an Int32 in the range 0-15 into a the corresponding char in hexadecimal. One really dummy solution consists in writing

var hex = new[] {'0', '1', '2', '3', '4', '5', '6', '7', 
                 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
var myCharInHex = hex[myValue];

Yet, this solution looks plain wrong, any better suggestion?

Joannes Vermorel
  • 8,976
  • 12
  • 64
  • 104
  • 1
    if you are completely sure that your int is always in that range and you want a mapping of int->char I find your solution plain excellent :) – flq Jun 08 '09 at 15:30
  • Duplicate of http://stackoverflow.com/questions/74148/how-to-convert-numbers-between-hex-and-decimal-in-c – Binary Worrier Jun 08 '09 at 15:32

2 Answers2

4

That works for your exact specification, but I'd personally do it as:

private static readonly char[] HexDigits = "0123456789abcdef".ToCharArray();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

This simple code must work:

string hexValue = myValue.ToString("X");
tekBlues
  • 5,745
  • 1
  • 29
  • 32