Convert string to hex-string in C#

62

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.

This question is tagged with c# .net string hex

~ Asked on 2013-06-08 12:37:17

The Best Answer is


150

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.

~ Answered on 2013-06-08 12:41:54


23

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

~ Answered on 2013-06-08 12:48:36


Most Viewed Questions: