94

I have a string like "sample". I want to get a string of it in hex format; like this:

"796173767265"

Please give the C# syntax.

live2
  • 3,771
  • 2
  • 37
  • 46
Dariush Jafari
  • 5,223
  • 7
  • 42
  • 71
  • Which hex format are you talking about? ASCII? (The example you give is not ASCII for "sample"; is that a reference address?) Little endian, or big? What size? – jpaugh Jun 08 '13 at 12:40
  • 5
    https://stackoverflow.com/a/65508621/532647 the not-most-upvoted answer has a built-in .NET 5 helper, linking from here for more visibility – Iarek Jun 10 '21 at 13:47

7 Answers7

190

First you'll need to get it into a byte[], so do this:

byte[] ba = Encoding.Default.GetBytes("sample");

and then you can get the string:

var hexString = BitConverter.ToString(ba);

now, that's going to return a string with dashes (-) in it so you can then simply use this:

hexString = hexString.Replace("-", "");

to get rid of those if you want.

NOTE: you could use a different Encoding if you needed to.

T.S.
  • 18,195
  • 11
  • 58
  • 78
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
  • 1
    Using the Default Encoding could fail in any case? Running on different versions of Windows for example? – jacktric Sep 05 '16 at 08:49
  • 2
    @jacktric if you know the encoding you should always use the specific encoding. However, I've been using the `Default` encoding for more than a decade and haven't had issues in production across geographic locations or versions of Windows. – Mike Perrenoud Sep 06 '16 at 12:41
  • What if you want it to go the other way around? So from a variable which is a string in hex to a string with only alphanumerals? – CCG Nov 02 '21 at 14:48
49

In .NET 5.0 and later you can use the Convert.ToHexString() method.

using System;
using System.Text;

string value = "Hello world";

byte[] bytes = Encoding.UTF8.GetBytes(value);

string hexString = Convert.ToHexString(bytes);

Console.WriteLine($"String value: \"{value}\"");
Console.WriteLine($"   Hex value: \"{hexString}\"");

Running the above example code, you would get the following output:

String value: "Hello world"
   Hex value: "48656C6C6F20776F726C64"
Martin Costello
  • 9,672
  • 5
  • 60
  • 72
  • 5
    Great answer, I didn't know .NET had finally included a built-in way to convert strings to hex! (Not just Base64!) Thanks! – Momoro Feb 04 '21 at 06:16
30

For Unicode support:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}
franckspike
  • 2,039
  • 25
  • 18
26
var result = string.Join("", input.Select(c => ((int)c).ToString("X2")));

OR

var result  =string.Join("", 
                input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c))));
svick
  • 236,525
  • 50
  • 385
  • 514
Damith
  • 62,401
  • 13
  • 102
  • 153
  • 3
    You could simplify that to `((int)c).ToString("X")`. – svick Jun 08 '13 at 14:43
  • 2
    Actually, I realized this would be wrong for any characters ≤ 0x0F, because of the missing zero padding. To fix that, use `ToString("X2")`. – svick Jun 08 '13 at 17:08
  • 1
    The first one worked for me on `dot42` it takes about 10 seconds to process 4096bytes but I needed it for debugging and it worked as opposed to the BitConverter that just hangs. +1 – Piotr Kula Aug 06 '14 at 21:28
14

According to this snippet here, this approach should be good for long strings:

private string StringToHex(string hexstring)
{
    StringBuilder sb = new StringBuilder();
    foreach (char t in hexstring)
    { 
        //Note: X for upper, x for lower case letters
        sb.Append(Convert.ToInt32(t).ToString("x2")); 
    }
    return sb.ToString();
}

usage:

string result = StringToHex("Hello world"); //returns "48656c6c6f20776f726c64"

Another approach in one line

string input = "Hello world";
string result = String.Concat(input.Select(x => ((int)x).ToString("x2")));
fubo
  • 44,811
  • 17
  • 103
  • 137
7

few Unicode alternatives

var s = "0";

var s1 = string.Concat(s.Select(c => $"{(int)c:x4}"));  // left padded with 0 - "0030d835dfcfd835dfdad835dfe5d835dff0d835dffb"

var sL = BitConverter.ToString(Encoding.Unicode.GetBytes(s)).Replace("-", "");       // Little Endian "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
var sB = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(s)).Replace("-", ""); // Big Endian "0030D835DFCFD835DFDAD835DFE5D835DFF0D835DFFB"

// no encodding "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
byte[] b = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, b, 0, b.Length);
var sb = BitConverter.ToString(b).Replace("-", "");
Slai
  • 22,144
  • 5
  • 45
  • 53
1

In case detailed conversion with regard to endianness of bytes or words is required, here is an example of the craft to do bitwise conversion.

var bcd = new byte[] { 64, 7, 19, 0, 0, 0 };
var str = String.Join("", bcd.Reverse().Select(b => $"{b:X2}"));

str => 000000317004

To also swap 4-bit nibbles of each byte, shift and mask to format each 4 bit separately.

var bcd = new byte[] { 64, 7, 19, 0, 0, 0 };
var str = String.Join("", bcd.Reverse().Select(b => $"{b & 0x0F:X1}{b>>4:X1}"));

str => 000000130740

flodis
  • 1,123
  • 13
  • 9