Main Site Documentation

Best way to convert an integer to hexadecimal string?


#1

Hi,im trying to perform a function to make a convertion like .ToString(“X”)

I need to convert a int value like 1023 to its hex representation but in a string format like this: “3FF”.

now looking in fezzer.com i found a function that converts a byte to a hex string but i need more range and no only the top 255 (FF).

i’m using a panda, and the sdk 4.1 :slight_smile:


#2

Use the fezzer code and just shift as you need greater range.

http://www.fezzer.com/project/84/convert-byte-to-hex-string/

For instance mask with 0xF000 >> 12 gives you an index into the hex string that represents the highest order 4 bits; 0xF00 >> 8 gives next 4, and so on


#3

thanks for your help.

i modified the function adding an extra range and works fine ;D.

here is the final function.


public string Byte_ToHex(int number) 
        { 
            string hex = "0123456789ABCDEF";
            return new string(new char[] { hex[(number & 0xF000) >> 12], hex[(number & 0xF00) >> 8], hex[(number & 0xF0) >> 4], hex[number & 0x0F] });
        }

also i put this topic in fezzer.com so it can be useful to someone else 8)


#4

Here is the link :slight_smile:

http://www.fezzer.com/project/258/int-to-hex-conversion-with-extended-range/


#5

I have added this before, but I rather like this function from Jens Kuhner’s book


public static string ByteToHex(byte b)
        {
            const string hex = "0123456789ABCDEF";
            int lowNibble = b & 0x0F;
            int highNibble = (b & 0xF0) >> 4;
            string s = new string(new char[] { hex[highNibble], hex[lowNibble] });
            return s;
        }


#6

Below is a little code to make it an extension method, so you can use it like this:


byte b = 42;
b.ToHexString(); 


namespace TestProgram
{
  public static class Extensions
  {
    const string hex = "0123456789ABCDEF";

    public static string ToHexString(this byte b)
    {
      int lowNibble = b & 0x0F;
      int highNibble = (b & 0xF0) >> 4;
      string s = new string(new char[] { hex[highNibble], hex[lowNibble] });
      return s;
    }

    public static string ToHexString(this int i)
    {
      int nibble0 = i & 0x000F;
      int nibble1 = (i & 0x00F0) >> 4;
      int nibble2 = (i & 0x0F00) >> 8;
      int nibble3 = (i & 0xF000) >> 12;
      string s = new string(new char[] { hex[nibble3], hex[nibble2], 
                                         hex[nibble1], hex[nibble0] });
      return s;
    }
  }
}

namespace System.Runtime.CompilerServices
{
  public class ExtensionAttribute : Attribute { }
}


#7
  1. ok, i think yours can be a more useful way to make the conversion. thanks ;D