Convert string to hex-string in C#
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.
Converting string value to hex decimal
An int contains a number, not a representation of the number. 12000 is equivalent to 0x2ee0:
int a = 12000;
int b = 0x2ee0;
a == b
You can convert from the string "12000" to an int using int.Parse(). You can format an int as hex with int.ToString("X").
C# send hex string as hex
You, probably, are looking for parsing (each string
item like "0x5C"
should be parsed into corresponding byte
: 0x5C
):
string Start = "0x5C 0x21 0x5C";
byte[] ByteMessage = Start
.Split(' ') // Split string into items
.Select(item => Convert.ToByte(item, 16)) // Parse items into corresponding bytes
.ToArray(); // Materialize into array
// Back to Hex (let's have a look on what we are going to send): "5C-21-5C"
string HexMessage = string.Join("-", ByteMessage
.Select(item => item.ToString("X2")));
String to byte hex convert
Try Convert.ToByte while providing fromBase
(16
in your case)
// "0A" (string) -> 0x0A == 10 == 0b00001010 (byte)
byte result = Convert.ToByte(hexString, 16);
...
SomeApiMethod(..., result, ...);
In case you have a Int32
encoded in fact (e.g. "FF120A"
) and you want to get the last byte:
// "FF120A" (or "0xFF120A") -> 0xFF120A (int) -> 0x0A (byte)
// unchecked - we don't want OverflowException on integer overflow
byte result = unchecked((byte)Convert.ToInt32(hexString, 16));
...
SomeApiMethod(..., result, ...);
Please, notice that the byte
(e.g. 0x0A
) is always the same, it its string representation that can vary:
// 00001010 - binary
Console.WriteLine(Convert.ToString(result, 2).PadLeft(8, '0'));
// 10 - decimal
Console.WriteLine(result);
// 0A - hexadecimal
Console.WriteLine(result.ToString("X2"));
Converting String to Hex then into Byte Array
If your final aim is to send byte[]
, then you can actually skip the middle step and immediately do the conversion from string
to byte[]
using Encoding.ASCII.GetBytes
(provided that you send ASCII char):
string beforeConverting = "HELLO";
byte[] byteData = Encoding.ASCII.GetBytes(beforeConverting);
//will give you {0x48, 0x45, 0x4C, 0x4C, 0x4F};
If you don't send ASCII, you could find the appropriate Encoding type (like Unicode or UTF32), depends on your need.
That being said, if you still want to convert the hex string to byte array, you could do something something like this:
/// <summary>
/// To convert Hex data string to bytes (i.e. 0x01455687) given the data type
/// </summary>
/// <param name="hexString"></param>
/// <param name="dataType"></param>
/// <returns></returns>
public static byte[] HexStringToBytes(string hexString) {
try {
if (hexString.Length >= 3) //must have minimum of length of 3
if (hexString[0] == '0' && (hexString[1] == 'x' || hexString[1] == 'X'))
hexString = hexString.Substring(2);
int dataSize = (hexString.Length - 1) / 2;
int expectedStringLength = 2 * dataSize;
while (hexString.Length < expectedStringLength)
hexString = "0" + hexString; //zero padding in the front
int NumberChars = hexString.Length / 2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hexString)) {
for (int i = 0; i < NumberChars; i++)
bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
return bytes;
} catch {
return null;
}
}
And then use it like this:
byte[] byteData = afterConverting.Select(x => HexStringToBytes(x)[0]).ToArray();
The method I put above is more general which can handle input string
like 0x05163782
to give byte[4]
. For your use, you only need to take the first byte (as the byte[]
will always be byte[1]
) and thus you have [0]
index in the LINQ Select
.
The core method used in the custom method above is Convert.ToByte()
:
bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
How to Convert Hex String to Hex Number
Convert.ToInt32("3A", 16)
Related Topics
How to Run and Interact with an Async Task from a Wpf Gui
Why Are C# Interface Methods Not Declared Abstract or Virtual
How Would You Make a Unique Filename by Adding a Number
Convert String to Hex-String in C#
C# Reflection and Finding All References
Compare Nullable Types in Linq to SQL
Exception When Addwithvalue Parameter Is Null
Creating Composite Key Entity Framework
Should You Implement Idisposable.Dispose() So That It Never Throws
Is It Ok to Use a String as a Lock Object
How to Set Up HTML/Email Templates with ASP.NET
Build Error: You Must Add a Reference to System.Runtime
Getting the "Diff" Between Two Arrays in C#
Webapi Streamcontent VS Pushstreamcontent