Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to hex-string in C#

Tags:

string

c#

.net

hex

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.

like image 469
Dariush Jafari Avatar asked Jun 08 '13 12:06

Dariush Jafari


People also ask

What is Strtol function in C?

The strtol library function in C converts a string to a long integer. The function works by ignoring any whitespace at the beginning of the string, converting the next characters into a long integer, and stopping when it comes across the first non-integer character.

What Atoi does in C?

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.

Is there a hex type in C?

There is no special type of data type to store Hexadecimal values in C programming, Hexadecimal number is an integer value and you can store it in the integral type of data types (char, short or int). Let suppose, we have two values in Hexadecimal "64" (100 in Decimal) and "FAFA" (64250 in Decimal).


2 Answers

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.

like image 111
Mike Perrenoud Avatar answered Oct 03 '22 17:10

Mike Perrenoud


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"     } } 
like image 26
franckspike Avatar answered Oct 03 '22 17:10

franckspike