How to Convert a Byte Array to a Hexadecimal String, and Vice Versa

How do you convert a byte array to a hexadecimal string, and vice versa?

You can use Convert.ToHexString starting with .NET 5.

There's also a method for the reverse operation: Convert.FromHexString.


For older versions of .NET you can either use:

public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}

or:

public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-","");
}

There are even more variants of doing it, for example here.

The reverse conversion would go like this:

public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}

Using Substring is the best option in combination with Convert.ToByte. See this answer for more information. If you need better performance, you must avoid Convert.ToByte before you can drop SubString.

How to convert a byte array to a hex string in Java?

From the discussion here, and especially this answer, this is the function I currently use:

private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}

My own tiny benchmarks (a million bytes a thousand times, 256 bytes 10 million times) showed it to be much faster than any other alternative, about half the time on long arrays. Compared to the answer I took it from, switching to bitwise ops --- as suggested in the discussion --- cut about 20% off of the time for long arrays. (Edit: When I say it's faster than the alternatives, I mean the alternative code offered in the discussions. Performance is equivalent to Commons Codec, which uses very similar code.)

2k20 version, with respect to Java 9 compact strings:

private static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
public static String bytesToHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}

I want to convert a hexadecimal byte array to hexadecimal in string format

def format_bytes_as_hex(b: bytes) -> str:
h = b.hex()
return ' ' .join(f'{a}{b}'.upper() for a, b in zip(h[0::2], h[1::2]))


Test:
format_bytes_as_hex(b'\xfc\x81\xe4\xa2\xb9\x92')
'FC 81 E4 A2 B9 92'

How do you convert a byte array to a hexadecimal string, and vice versa?

You can use Convert.ToHexString starting with .NET 5.

There's also a method for the reverse operation: Convert.FromHexString.


For older versions of .NET you can either use:

public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}

or:

public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-","");
}

There are even more variants of doing it, for example here.

The reverse conversion would go like this:

public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}

Using Substring is the best option in combination with Convert.ToByte. See this answer for more information. If you need better performance, you must avoid Convert.ToByte before you can drop SubString.

Converting a byte array into a hex string

As I am on Kotlin 1.3 you may also be interested in the UByte soon (note that it's an experimental feature. See also Kotlin 1.3M1 and 1.3M2 announcement)

E.g.:

@ExperimentalUnsignedTypes // just to make it clear that the experimental unsigned types are used
fun ByteArray.toHexString() = asUByteArray().joinToString("") { it.toString(16).padStart(2, '0') }

The formatting option is probably the nicest other variant (but maybe not that easily readable... and I always forget how it works, so it is definitely not so easy to remember (for me :-)):

fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }

Why to convert byte array to hex string?

For example:

  • To store in a file with a format that doesn't support binary, e.g. CSV.
  • To store in a database field that doesn't support binary.
  • To send in a protocol that doesn't support binary.
  • To embed in other content that doesn't support binary, e.g. XML and JSON.
  • To display to a user.
  • Many other reasons...

How do you convert a byte array to a hexadecimal string, and vice versa?

You can use Convert.ToHexString starting with .NET 5.

There's also a method for the reverse operation: Convert.FromHexString.


For older versions of .NET you can either use:

public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}

or:

public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-","");
}

There are even more variants of doing it, for example here.

The reverse conversion would go like this:

public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}

Using Substring is the best option in combination with Convert.ToByte. See this answer for more information. If you need better performance, you must avoid Convert.ToByte before you can drop SubString.

Convert byte array represented as hexadecimal string to correct int

Byte array contains the byte representation of a string.

In ASCII:

  • 102 == 'f'
  • 100 == 'd'
  • 51 == '3'
  • 52 == '4'
  • 48 == '0'

You should convert from byte array to string and then parse that string using base 16 (hexadecimal).

String hex = new String(arr, "ASCII"); //fd3400
int number = Integer.valueOf(hex, 16).intValue(); //16593920

C# - Fast Method to Convert Byte Array to Hex String

    private static string ByteArrayToHexViaLookup32(byte[] bytes)
{
var lookup32 = _lookup32;
var byteCount = bytes.Length;
var result = new char[3* byteCount - 1];
for (int i = 0; i < byteCount; i++)
{
var val = lookup32[bytes[i]];
int index = 3 * i;
result[index] = (char)val;
result[index + 1] = (char)(val >> 16);
if (i < byteCount - 1) result[index + 2] = ' ';
}
return new string(result);
}


Related Topics



Leave a reply



Submit