Byte Array to Hexadecimal String

Lookup

  • Text: 23,879.41 (20.8X faster)
  • Sentence: 1.15 (23.9X faster)
/// <summary>
/// Hex string lookup table.
/// </summary>
private static readonly string[] HexStringTable = new string[]
{
    "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
    "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
    "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
    "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
    "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
    "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
    "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
    "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
    "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
    "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
    "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
    "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
    "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
    "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
    "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
    "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"
};

/// <summary>
/// Returns a hex string representation of an array of bytes.
/// </summary>
/// <param name="value">The array of bytes.</param>
/// <returns>A hex string representation of the array of bytes.</returns>
public static string ToHex(this byte[] value)
{
    StringBuilder stringBuilder = new StringBuilder();
    if (value != null)
    {
        foreach (byte b in value)
        {
            stringBuilder.Append(HexStringTable[b]);
        }
    }

    return stringBuilder.ToString();
}

The above approach runs 25% faster than using a small hex alphabet and doing something like:

  • Text: 23,201.23 (21.4X faster)
  • Sentence: 1.24 (22.3X faster)
StringBuilder stringBuilder = new StringBuilder();
string hexAlphabet = "0123456789ABCDEF";
if (value != null)
{
    foreach (byte b in value)
    {
        stringBuilder.Append(hexAlphabet[(int)(b >> 4)]);
        stringBuilder.Append(hexAlphabet[(int)(b & 0xF)]);
    }
}

BitConverter

  • Text: 113,269.34 (4.4X faster)
  • Sentence: 9.98 (2.8X faster)
public static string ByteArrayToString(byte[] ba)
{
  string hex = BitConverter.ToString(ba);
  return hex.Replace("-","");
}

StringBulider.AppendFormat

  • Text: 672,115.77 (1.1X faster)
  • Sentence: 36.82 (1.1X faster)
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();
}
  • Text: 718,380.63 (1.0X faster)
  • Sentence: 39.71 (1.0X faster)
        static string ByteArrayToHexStringViaStringBuilderAggregateAppendFormat(byte[] bytes)
        {
            return bytes.Aggregate(new StringBuilder(bytes.Length * 2), (sb, b) => sb.AppendFormat("{0:X2}", b)).ToString();
        }

Array.ConvertAll

  • Text: 752,078.70 (1.0X faster)
  • Sentence: 18.28 (2.2X faster)
        static string ByteArrayToHexStringViaStringConcatArrayConvertAll(byte[] bytes)
        {
            return string.Concat(Array.ConvertAll(bytes, b => b.ToString("X2")));
        }
  • Text: 675,451.57 (1.1X faster)
  • Sentence: 17.95 (2.2X faster)
        static string ByteArrayToHexStringViaStringJoinArrayConvertAll(byte[] bytes)
        {
            return string.Join(string.Empty, Array.ConvertAll(bytes, b => b.ToString("X2")));
        }

{byte}.ToString("x2")

  • Text: 308,805.38 (2.4X faster)
  • Sentence: 16.89 (2.4X faster)
        static string ByteArrayToHexStringViaStringBuilderForEachByteToString(byte[] bytes)
        {
            StringBuilder hex = new StringBuilder(bytes.Length * 2);
            foreach (byte b in bytes)
                hex.Append(b.ToString("X2"));
            return hex.ToString();
        }
  • Text: 352,828.20 (2.1X faster)
  • Sentence: 16.87 (2.4X faster)
        static string ByteArrayToHexStringViaStringBuilderAggregateByteToString(byte[] bytes)
        {
            return bytes.Aggregate(new StringBuilder(bytes.Length * 2), (sb, b) => sb.Append(b.ToString("X2"))).ToString();
        }

{SoapHexBinary}.ToString()

        static string ByteArrayToHexViaSoapHexBinary(byte[] bytes)
        {
            SoapHexBinary soapHexBinary = new SoapHexBinary(bytes);
            return soapHexBinary.ToString();
        }

Byte Manipulation

  • Text: 16,856.64 (29.5X faster)
  • Sentence: 0.70 (39.5X faster)
        static string ByteArrayToHexViaByteManipulation(byte[] bytes)
        {
            char[] c = new char[bytes.Length * 2];
            byte b;
            for (int i = 0; i < bytes.Length; i++)
            {
                b = ((byte)(bytes[i] >> 4));
                c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);
                b = ((byte)(bytes[i] & 0xF));
                c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);
            }
            return new string(c);
        }
  • Text: 12,967.69 (38.4X faster)
  • Sentence: 0.73 (37.9X faster)
        static string ByteArrayToHexViaByteManipulation2(byte[] bytes)
        {
            char[] c = new char[bytes.Length * 2];
            int b;
            for (int i = 0; i < bytes.Length; i++)
            {
                b = bytes[i] >> 4;
                c[i * 2] = (char)(55 + b + (((b - 10) >> 31) & -7));
                b = bytes[i] & 0xF;
                c[i * 2 + 1] = (char)(55 + b + (((b - 10) >> 31) & -7));
            }
            return new string(c);
        }

Quote From

How do you convert Byte Array to Hexadecimal String, and vice versa

byte[] to hex string

blambert/codesnip – Fast byte array to hex string conversion

时间: 2024-10-13 07:29:06

Byte Array to Hexadecimal String的相关文章

C#中使用Buffer.BlockCopy()方法将string转换为byte array的方法:

public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); 将指定数目的字节从起始于特定偏移量的源数组复制到起始于特定偏移量的目标数组. /// <summary> /// C#中使用Buffer.BlockCopy()方法将string转换为byte array的方法 /// </summary> /// <param name="str&

C# byte[]与char[]、string与char[]、byte[] 与 string 互转

1. byte array -> char array Byte[] b=new byte[5]{0x01,0x02,0x03,0x04,0x05}; Char[] c=Encoding.ASCII.GetChars(b); 2. char array -> byte array Char[] c=new char[5]{a,b,c,d,e}; Byte[] b=Encoding.Default.GetBytes(c); Char[] c=new char[5]{a,b,c,d,e}; Byt

vb.net中,如何把byte array还原成为包含中文的字符串

这个问题,在网上好找了半天,但说实在话,不得不说,现在的程序员,脑子都僵化了. 一个能解决的也没有. 这还不说,多数人指出应当两边都用UNICODE,不要用ASC 2码之类的.我想说,这些是人家问的吗?不懂就是不懂,要是我就这样,何必不懂还要瞎JB指挥? 但我要说,这正是知其然不知其所以然,正确的回答,永远是先解释完提出问题的人,然后解决之. 然后,如果你愿意画蛇添足,再加上自己的想法.不想多说了,正确的代码我放在这里: '====================================

Byte Array to NSData——iOS将服务器返回的图片字节数组用UIImageView显示该图像

前言:我现在做的项目中 服务器返回的图片格式是 图片字节数组,需要把字节数组转换成data然后用imageView展示出来.真是服了服务器工程师了!!!折腾半天终于找到答案,记录下来. 下面是stackOverflow中找到的答案: http://stackoverflow.com/questions/11860830/byte-array-to-nsdata Byte Array to NSData up vote10down votefavorite 5 In a WebService JS

How to convert a byte to its binary string representation

How to convert a byte to its binary string representation For example, the bits in a byte B are 10000010, how can I assign the bits to the string strliterally, that is, str = "10000010". byte b1 = (byte) 129; String s1 = String.format("%8s&

Java之byte、char和String类型相互转换

1 package basictype; 2 3 /** 4 * byte.char和String类型相互转换 5 */ 6 public class CHJavaType { 7 public static void main(String[] args) { 8 String string = "abcd"; 9 10 // String转char[] 11 char[] chars = string.toCharArray(); 12 for (char c : chars) {

Delphi Byte数组与Int String之间的相互转换

http://www.cnblogs.com/lcw/p/3352864.html string string = AnsiString = 长字符串,理论上长度不受限制,但其实受限于最大寻址范围2的32次方=4G字节: 变量Str名字是一个指针,指向位于堆内存的字符序列,字符序列起始于@Str[1],@Str[1]偏移负16个字节的空间存储着字串长度.引用计数等信息.字符序列以NULL结束. string[n] string[n] = ShortString = 短字符串,最多容纳255个字符

js Array对象和String对象常用方法整理

我们总是频繁的对数组和字符串进行操作,今天整理一下这些常用的方法.复习的时候写一写 不然会忘掉一些小细节==. 一,String对象 1.跟位置有关的 charAt()  返回在指定位置的字符 charAtCodeAt()   方法可返回指定位置的字符的 Unicode 编码 indexOf()  从头检索字符串 lastIndexOf()  从后向前检索字符串 2.根据索引提取制定的字符串 slice()  提取字符串的片断,并在新的字符串中返回被提取的部分.  stringObjec.sli

C语言数据转换(hex - char - byte array - acsii)

网上的整理过来的,来源记不清了,感谢作者. DataConvert.c #include <stdio.h> #include <string.h> #include "DataConvert.h" int strToHex(char *ch, char *hex) { int high,low; int tmp = 0; if(ch == NULL || hex == NULL){ return -1; } if(strlen(ch) == 0){ retur