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[]
{
"", "", "", "", "", "", "", "", "", "", "0A", "0B", "0C", "0D", "0E", "0F",
"", "", "", "", "", "", "", "", "", "", "1A", "1B", "1C", "1D", "1E", "1F",
"", "", "", "", "", "", "", "", "", "", "2A", "2B", "2C", "2D", "2E", "2F",
"", "", "", "", "", "", "", "", "", "", "3A", "3B", "3C", "3D", "3E", "3F",
"", "", "", "", "", "", "", "", "", "", "4A", "4B", "4C", "4D", "4E", "4F",
"", "", "", "", "", "", "", "", "", "", "5A", "5B", "5C", "5D", "5E", "5F",
"", "", "", "", "", "", "", "", "", "", "6A", "6B", "6C", "6D", "6E", "6F",
"", "", "", "", "", "", "", "", "", "", "7A", "7B", "7C", "7D", "7E", "7F",
"", "", "", "", "", "", "", "", "", "", "8A", "8B", "8C", "8D", "8E", "8F",
"", "", "", "", "", "", "", "", "", "", "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 >> )]);
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 * );
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 * ), (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 * );
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 * ), (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 * ];
byte b;
for (int i = ; i < bytes.Length; i++)
{
b = ((byte)(bytes[i] >> ));
c[i * ] = (char)(b > ? b + 0x37 : b + 0x30);
b = ((byte)(bytes[i] & 0xF));
c[i * + ] = (char)(b > ? 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 * ];
int b;
for (int i = ; i < bytes.Length; i++)
{
b = bytes[i] >> ;
c[i * ] = (char)( + b + (((b - ) >> ) & -));
b = bytes[i] & 0xF;
c[i * + ] = (char)( + b + (((b - ) >> ) & -));
}
return new string(c);
}

Lookup by byte

  • Text: 10,853.96 (45.8X faster)
  • Sentence: 0.65 (42.7X faster)
private static readonly uint[] _lookup32 = CreateLookup32();

private static uint[] CreateLookup32()
{
var result = new uint[];
for (int i = ; i < ; i++)
{
string s=i.ToString("X2");
result[i] = ((uint)s[]) + ((uint)s[] << );
}
return result;
} private static string ByteArrayToHexViaLookup32(byte[] bytes)
{
var lookup32 = _lookup32;
var result = new char[bytes.Length * ];
for (int i = ; i < bytes.Length; i++)
{
var val = lookup32[bytes[i]];
result[*i] = (char)val;
result[*i + ] = (char) (val >> );
}
return new string(result);
}

Lookup by byte unsafe

private static readonly uint[] _lookup32Unsafe = CreateLookup32Unsafe();
private static readonly uint* _lookup32UnsafeP = (uint*)GCHandle.Alloc(_lookup32Unsafe,GCHandleType.Pinned).AddrOfPinnedObject(); private static uint[] CreateLookup32Unsafe()
{
var result = new uint[];
for (int i = ; i < ; i++)
{
string s=i.ToString("X2");
if(BitConverter.IsLittleEndian)
result[i] = ((uint)s[]) + ((uint)s[] << );
else
result[i] = ((uint)s[]) + ((uint)s[] << );
}
return result;
} public static string ByteArrayToHexViaLookup32Unsafe(byte[] bytes)
{
var lookupP = _lookup32UnsafeP;
var result = new char[bytes.Length * ];
fixed(byte* bytesP = bytes)
fixed (char* resultP = result)
{
uint* resultP2 = (uint*)resultP;
for (int i = ; i < bytes.Length; i++)
{
resultP2[i] = lookupP[bytesP[i]];
}
}
return new string(result);
}

Or if you consider it acceptable to write into the string directly:

public static string ByteArrayToHexViaLookup32UnsafeDirect(byte[] bytes)
{
var lookupP = _lookup32UnsafeP;
var result = new string((char), bytes.Length * );
fixed (byte* bytesP = bytes)
fixed (char* resultP = result)
{
uint* resultP2 = (uint*)resultP;
for (int i = ; i < bytes.Length; i++)
{
resultP2[i] = lookupP[bytesP[i]];
}
}
return result;
}

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

Byte Array to Hexadecimal String的更多相关文章

  1. Convert a byte[] array to readable string format. This makes the "hex" readable!

    /* * Java Bittorrent API as its name indicates is a JAVA API that implements the Bittorrent Protocol ...

  2. C# byte array 跟 string 互转

    用 System.Text.Encoding.Default.GetString() 转换时,byte array 中大于 127 的数据转 string 时会出问题. 把这里的 Default 换成 ...

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

    public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); 将指定数目的字 ...

  4. 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.AS ...

  5. Java中如何正确的将byte[]数组转化为String类型?

    很多人在编程时,总是喜欢用一下方法将数组转为字符串:(a为byte数组) String s=a.toString(); 可是每次返回的时候,新手看来返回的结果是乱码,比如说我,写RSA算法时,没有注意 ...

  6. PHP write byte array to file

    /********************************************************************************* * PHP write byte ...

  7. perl malformed JSON string, neither tag, array, object, number, string or atom, at character offset

    [root@wx03 ~]# cat a17.pl use JSON qw/encode_json decode_json/ ; use Encode; my $data = [ { 'name' = ...

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

    package basictype; /** * byte.char和String类型相互转换 */ public class CHJavaType { public static void main ...

  9. 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 1000 ...

随机推荐

  1. Ext.ux.form.SuperBoxSelect

    Ext.ux.form.SuperBoxSelect 在B/S系统中,下拉列表(select/dropdownlist/combobox)的应用随处可见,为了增强用户体验,开发人员也常常会做一些带联想 ...

  2. HttpMessageHandler管道[上篇]

    HttpMessageHandler管道[上篇] 整个ASP.NET Web API服务端框架采用管道式设计,这个用于“处理请求.响应回复”的管道本质上就是一组HttpMessageHandler的有 ...

  3. Chrome新的语言API,让您的浏览器说话

    还记得曾经那个能识别语音的API吗?当时一直在想,如果能让浏览器替我念出文字就好了.现在chrome的最新版本Version 33 中您只要按F12然后在console里面输入这段代码,您就能听到浏览 ...

  4. Android 关于ListView中按钮监听的优化问题(方法一)

    在Android应用开发过程中经常会用到ListView,并且每次在item中都要对点击事件进行监听.在给按钮添加OnClickListener时,一般会下意识的在getView()中找到每一个But ...

  5. 轻松搞定javascript日期格式化问题

    Date.prototype.format = function(f){ var d = this f = f || "yyyy-MM-dd hh:mm:ss" return f. ...

  6. Promise初体验

    想通过回调函数做一个动画效果:三个小球依次运动,第一个小球运动到指定位置后回调第二个小球运动,依次类推,效果如图所示: 到第三个小球到达指定位置再回调,让第二个小球往回移动,直到最后一个小球回到原位: ...

  7. [ios2] CABasicAnimation【转】

    caanimation 整理了解  http://geeklu.com/2012/09/animation-in-ios/ 几个可以用来实现热门APP应用PATH中menu效果的几个方法 +(CABa ...

  8. Android自定义控件系列(二)—icon+文字的多种效果实现

    转载请注明出处:http://www.cnblogs.com/landptf/p/6290810.html 今天给大家带来一个很简单但是很常用的控件ButtonExtendM,在开发中我们经常会用到图 ...

  9. MySQL闪回原理与实战

    本文将介绍闪回原理,给出笔者的实战经验,并对现存的闪回工具作比较. DBA或开发人员,有时会误删或者误更新数据,如果是线上环境并且影响较大,就需要能快速回滚.传统恢复方法是利用备份重搭实例,再应用去除 ...

  10. liunx系统磁盘满的时候如何排查

    第一步:查看磁盘总体情况 命令: df -lh 可以看出/dev/vda1, 不过这是个设备的名称不是对应的目录,其实/dev/vda1设备对应的目录名称是/home下面 或者可以全局搜索哪个目录下面 ...