How can I convert a hex string to a byte array?
Here's a nice fun LINQ example.
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
C# - Convert hex string to byte array of hex values
string hexIpAddress = "0A010248"; // 10.1.2.72 => "0A010248"
byte[] bytes = new byte[hexIpAddress.Length / 2];
for (int i = 0; i < hexIpAddress.Length; i += 2)
bytes[i/2] = Convert.ToByte(hexIpAddress.Substring(i, 2), 16);
This results in this array:
bytes = {0x0A, 0x01, 0x02, 0x48};
or represented as decimals:
bytes = {10, 1, 2, 72};
or as binaries 00001010
, 000000001
, 00000010
, 01001000
(binary literals are still not supported in C#6).
The values are the same, there is no representation in any base in byte
. You can only decide how the values should be represented when converting them to strings again:
foreach(byte b in bytes)
Console.WriteLine("{0} {0:X}", b);
results in
10 A
1 1
2 2
72 48
c# string to hex , hex to byte conversion
You can use the Convert.ToByte(String, Int32)
method with the base set to 16 (hexadecimal):
String text = "d7";
byte value = Convert.ToByte(text, 16);
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"));
C# Convert Hex String Array to Byte Array
You have to convert (or parse) string
in order to get byte
since string
and byte
are different types:
// 10 == 10d
byte b = Convert.ToByte("10"); // if "10" is a decimal representation
// 16 == 0x10
byte b = Convert.ToByte("10", 16); // if "10" is a hexadecimal representation
If you want to process an array, you can try a simple Linq:
using System.Linq;
...
string[] hexValues = new string[] {
"10", "0F", "3E", "42"};
byte[] result = hexValues
.Select(value => Convert.ToByte(value, 16))
.ToArray();
If you want to print out result
as hexadecimal, use formatting ("X2"
format string - at least 2
hexadecimal digits, use captital letters):
// 10, 0F, 3E, 42
Console.Write(string.Join(", ", result.Select(b => b.ToString("X2"))));
Compare with same array but in a different format ("d2"
- at least 2
decimal digits)
// 16, 15, 62, 66
Console.Write(string.Join(", ", result.Select(b => b.ToString("d2"))));
If no format provided, .Net uses default one and represents byte
in decimal:
// 16, 15, 62, 66
Console.Write(string.Join(", ", result));
Hex String To Byte Array C#
I believe you can use Convert.ToByte(), you might have to slice your string in pairs and loop through it.
If you do a quick search there are many topics on this already on stackoverflow
How do you convert Byte Array to Hexadecimal String, and vice versa?
You can also look at this MS example, it is to convert to int, but the idea is the same.
http://msdn.microsoft.com/en-us/library/bb311038.aspx
how to convert hex string values to byte[] in c#
Try Linq: Split
and Convert
string source = "FF AA 1A 23 DF";
byte[] result = source
.Split(' ') // Split into items
.Select(item => Convert.ToByte(item, 16)) // Convert each item into byte
.ToArray(); // Materialize as array
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);
Related Topics
How to Asynchronously Wait for X Seconds and Execute Something Then
Launch an Application and Send It to Second Monitor
How to Convert a List to Ienumerable
Comparing Two Lists and Return Not Matching Items Results With Error
How to Use Variable in Feature File
How to Open a Url in Chrome Incognito Mode
How to Disable Uwp App Suspension
Regular Expression for Password Validation in C#
How to Dynamically Adjust Table Column Width in Rdlc Report
Using Recursion to Add Odd Numbers
How to Call a Button Click Event from Another Method
How to Encrypt a Password Within Appsettings.Json for ASP.NET Core 2
How to Set the Selected Item in a Combobox to Match My String Using C#
Json Deserializer Returning Null Values
Convert String to Given Regex Pattern
How to Handle [Null] Values of Datetime from SQL Server to a Datetimepicker
How to Convert String Formula to a Mathematical Formula in C#
File Being Used by Another Process After Using File.Create()