How to Convert byte array to hex string in C#
By FoxLearn 10/29/2024 2:43:28 PM 127
To convert a byte array to a concatenated hex string in .NET, you can use the static BitConverter.ToString()
method. This simplifies the process by handling the conversion for you, making it easy to get the desired hex format.
For example:
byte[] byteArray = { 0x01, 0xA0, 0xFF, 0x10 }; string hexString = BitConverter.ToString(byteArray).Replace("-", "").ToLower(); Console.WriteLine(hexString); // Output: 01a0ff10
The BitConverter.ToString()
concatenates each byte with dashes. To remove the dashes and get a continuous hex string, you can replace them with an empty string.
If you prefer to format the string manually, you can use StringBuilder
:
byte[] byteArray = { 0x01, 0xA0, 0xFF, 0x10 }; var hexStringBuilder = new StringBuilder(); foreach (byte b in byteArray) hexStringBuilder.AppendFormat("{0:x2}", b); string hexString = hexStringBuilder.ToString(); Console.WriteLine(hexString); // Output: 01a0ff10
To convert a byte array to a string array, you can use a for loop, but a simpler approach is to utilize LINQ for more concise code.
string[] strArray = byteArray.Select(p => p.ToString("x2")).ToArray();
Each element of the array produces a lowercase hex string by default. However, you can use .ToString("X2")
to obtain an uppercase hex string.
- How to fix 'Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on'
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#