---
title: "How do you convert Byte Array to Hexadecimal String, and vice-versa?"  
description: "How do you convert Byte Array to Hexadecimal String, and vice-versa?"  
author: "Anonymous User"  
published: 2013-05-29  
updated: 2013-05-29  
canonical: https://www.mindstick.com/forum/933/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa  
category: "c#"  
tags: ["c#"]  
reading_time: 2 minutes  

---

# How do you convert Byte Array to Hexadecimal String, and vice-versa?

Hi Everyone!\
This is probably a [common](https://www.mindstick.com/articles/23170/10-most-common-accounting-mistakes-of-small-business) [question](https://www.mindstick.com/blog/23175/how-to-solve-neet-question-paper-in-less-time) over the [Internet](https://www.mindstick.com/articles/44650/what-should-you-do-during-an-internet-outage), but I couldn't find an answer that neatly explains how you can [convert](https://www.mindstick.com/forum/2093/configurationmanager-appsettings-convert-n-to-n-why) a [byte array](https://www.mindstick.com/forum/33877/char-array-to-byte-array-conversion-and-convert-back-again-to-char-arrray) to a hexadecimal [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp), and vice-versa.\
Thanks in advance.

## Replies

### Reply by AVADHESH PATEL

Hi John!\
**Either:**\

```
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){  string hex = BitConverter.ToString(ba);  return hex.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;}
```

Edit: you can improve performance for long strings by using a single pass parser, like so:\

```
public static byte[] StringToByteArray(String hex){  int NumberChars = hex.Length/2;  byte[] bytes = new byte[NumberChars];  StringReader sr = new StringReader(hex);  for (int i = 0; i < NumberChars; i++)    bytes[i] = Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);  sr.Dispose();  return bytes;}
```


---

Original Source: https://www.mindstick.com/forum/933/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
