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.
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.
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.
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).
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.
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" } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With