Skip to content

Instantly share code, notes, and snippets.

@yinyue200
Last active July 6, 2017 03:48
Show Gist options
  • Save yinyue200/7a8f38457fe4135cf300e4896b72c4ef to your computer and use it in GitHub Desktop.
Save yinyue200/7a8f38457fe4135cf300e4896b72c4ef to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Text;
namespace yfxsApp.Core
{
public static class HexExtensionMethods
{
public static string ToHex(this byte[] data)
{
return ToHex(data, string.Empty);
}
public static string ToHex(this byte[] data, string prefix)
{
char[] lookup = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
int i = 0, p = prefix.Length, l = data.Length;
char[] c = new char[l * 2 + p];
byte d;
for (; i < p; ++i) c[i] = prefix[i];
i = -1;
--l;
--p;
while (i < l)
{
d = data[++i];
c[++p] = lookup[d >> 4];
c[++p] = lookup[d & 0xF];
}
return new string(c, 0, c.Length);
}
public static byte[] FromHex(this string str)
{
return FromHex(str, 0, 0, 0);
}
public static byte[] FromHex(this string str, int offset, int step)
{
return FromHex(str, offset, step, 0);
}
public static byte[] FromHex(this string str, int offset, int step, int tail)
{
byte[] b = new byte[(str.Length - offset - tail + step) / (2 + step)];
byte c1, c2;
int l = str.Length - tail;
int s = step + 1;
for (int y = 0, x = offset; x < l; ++y, x += s)
{
c1 = (byte)str[x];
if (c1 > 0x60) c1 -= 0x57;
else if (c1 > 0x40) c1 -= 0x37;
else c1 -= 0x30;
c2 = (byte)str[++x];
if (c2 > 0x60) c2 -= 0x57;
else if (c2 > 0x40) c2 -= 0x37;
else c2 -= 0x30;
b[y] = (byte)((c1 << 4) + c2);
}
return b;
}
}
}
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment