Is there a Java equivalent for C#'s HttpServerUtility.UrlTokenDecode? - c#

How do I decode in Java a string that was encoded in C# using HttpServerUtility.UrlTokenEncode?

I tried using org.apache.commons.codec.binary.Base64 (The ctor accepts a parameter stating whether the encoding/decoding is url-safe) but turns out it is not implemented the same as UrlTokenEncode/Decode.
I ended up migrating the C# implementation to Java:
public static byte[] UrlTokenDecode(String input) {
if (input == null)
return new byte[0];
int len = input.length();
if (len < 1)
return new byte[0];
///////////////////////////////////////////////////////////////////
// Step 1: Calculate the number of padding chars to append to this string.
// The number of padding chars to append is stored in the last char of the string.
int numPadChars = (int)input.charAt(len - 1) - (int)'0';
if (numPadChars < 0 || numPadChars > 10)
return null;
///////////////////////////////////////////////////////////////////
// Step 2: Create array to store the chars (not including the last char)
// and the padding chars
char[] base64Chars = new char[len - 1 + numPadChars];
////////////////////////////////////////////////////////
// Step 3: Copy in the chars. Transform the "-" to "+", and "*" to "/"
for (int iter = 0; iter < len - 1; iter++) {
char c = input.charAt(iter);
switch (c) {
case '-':
base64Chars[iter] = '+';
break;
case '_':
base64Chars[iter] = '/';
break;
default:
base64Chars[iter] = c;
break;
}
}
////////////////////////////////////////////////////////
// Step 4: Add padding chars
for (int iter = len - 1; iter < base64Chars.length; iter++) {
base64Chars[iter] = '=';
}
// Do the actual conversion
String assembledString = String.copyValueOf(base64Chars);
return Base64.decodeBase64(assembledString);
}

Related

How to convert a string of bits to a HEX [duplicate]

I'm looking for a way to convert a long string of binary to a hex string.
the binary string looks something like this "0110011010010111001001110101011100110100001101101000011001010110001101101011"
I've tried using
hex = String.Format("{0:X2}", Convert.ToUInt64(hex, 2));
but that only works if the binary string fits into a Uint64 which if the string is long enough it won't.
is there another way to convert a string of binary into hex?
Thanks
I just knocked this up. Maybe you can use as a starting point...
public static string BinaryStringToHexString(string binary)
{
if (string.IsNullOrEmpty(binary))
return binary;
StringBuilder result = new StringBuilder(binary.Length / 8 + 1);
// TODO: check all 1's or 0's... throw otherwise
int mod4Len = binary.Length % 8;
if (mod4Len != 0)
{
// pad to length multiple of 8
binary = binary.PadLeft(((binary.Length / 8) + 1) * 8, '0');
}
for (int i = 0; i < binary.Length; i += 8)
{
string eightBits = binary.Substring(i, 8);
result.AppendFormat("{0:X2}", Convert.ToByte(eightBits, 2));
}
return result.ToString();
}
This might help you:
string HexConverted(string strBinary)
{
string strHex = Convert.ToInt32(strBinary,2).ToString("X");
return strHex;
}
Convert.ToInt32("1011", 2).ToString("X");
For string longer than this, you can simply break it into multiple bytes:
var binary = "0110011010010111001001110101011100110100001101101000011001010110001101101011";
var hex = string.Join(" ",
Enumerable.Range(0, binary.Length / 8)
.Select(i => Convert.ToByte(binary.Substring(i * 8, 8), 2).ToString("X2")));
I came up with this method. I am new to programming and C# but I hope you will appreciate it:
static string BinToHex(string bin)
{
StringBuilder binary = new StringBuilder(bin);
bool isNegative = false;
if (binary[0] == '-')
{
isNegative = true;
binary.Remove(0, 1);
}
for (int i = 0, length = binary.Length; i < (4 - length % 4) % 4; i++) //padding leading zeros
{
binary.Insert(0, '0');
}
StringBuilder hexadecimal = new StringBuilder();
StringBuilder word = new StringBuilder("0000");
for (int i = 0; i < binary.Length; i += 4)
{
for (int j = i; j < i + 4; j++)
{
word[j % 4] = binary[j];
}
switch (word.ToString())
{
case "0000": hexadecimal.Append('0'); break;
case "0001": hexadecimal.Append('1'); break;
case "0010": hexadecimal.Append('2'); break;
case "0011": hexadecimal.Append('3'); break;
case "0100": hexadecimal.Append('4'); break;
case "0101": hexadecimal.Append('5'); break;
case "0110": hexadecimal.Append('6'); break;
case "0111": hexadecimal.Append('7'); break;
case "1000": hexadecimal.Append('8'); break;
case "1001": hexadecimal.Append('9'); break;
case "1010": hexadecimal.Append('A'); break;
case "1011": hexadecimal.Append('B'); break;
case "1100": hexadecimal.Append('C'); break;
case "1101": hexadecimal.Append('D'); break;
case "1110": hexadecimal.Append('E'); break;
case "1111": hexadecimal.Append('F'); break;
default:
return "Invalid number";
}
}
if (isNegative)
{
hexadecimal.Insert(0, '-');
}
return hexadecimal.ToString();
}
Considering four bits can be expressed by one hex value, you can simply go by groups of four and convert them seperately, the value won't change that way.
string bin = "11110110";
int rest = bin.Length % 4;
if(rest != 0)
bin = new string('0', 4-rest) + bin; //pad the length out to by divideable by 4
string output = "";
for(int i = 0; i <= bin.Length - 4; i +=4)
{
output += string.Format("{0:X}", Convert.ToByte(bin.Substring(i, 4), 2));
}
If you want to iterate over the hexadecimal representation of each byte in the string, you could use the following extension. I've combined Mitch's answer with this.
static class StringExtensions
{
public static IEnumerable<string> ToHex(this String s) {
if (s == null)
throw new ArgumentNullException("s");
int mod4Len = s.Length % 8;
if (mod4Len != 0)
{
// pad to length multiple of 8
s = s.PadLeft(((s.Length / 8) + 1) * 8, '0');
}
int numBitsInByte = 8;
for (var i = 0; i < s.Length; i += numBitsInByte)
{
string eightBits = s.Substring(i, numBitsInByte);
yield return string.Format("{0:X2}", Convert.ToByte(eightBits, 2));
}
}
}
Example:
string test = "0110011010010111001001110101011100110100001101101000011001010110001101101011";
foreach (var hexVal in test.ToHex())
{
Console.WriteLine(hexVal);
}
Prints
06
69
72
75
73
43
68
65
63
6B
If you're using .NET 4.0 or later and if you're willing to use System.Numerics.dll (for BigInteger class), the following solution works fine:
public static string ConvertBigBinaryToHex(string bigBinary)
{
BigInteger bigInt = BigInteger.Zero;
int exponent = 0;
for (int i = bigBinary.Length - 1; i >= 0; i--, exponent++)
{
if (bigBinary[i] == '1')
bigInt += BigInteger.Pow(2, exponent);
}
return bigInt.ToString("X");
}
Considering four bits can be expressed by one hex value, you can simply go by groups of four and convert them seperately, the value won't change that way.
string bin = "11110110";
int rest = bin.Length % 4;
bin = bin.PadLeft(rest, '0'); //pad the length out to by divideable by 4
string output = "";
for(int i = 0; i <= bin.Length - 4; i +=4)
{
output += string.Format("{0:X}", Convert.ToByte(bin.Substring(i, 4), 2));
}
static string BinToHex(string bin)
{
if (bin == null)
throw new ArgumentNullException("bin");
if (bin.Length % 8 != 0)
throw new ArgumentException("The length must be a multiple of 8", "bin");
var hex = Enumerable.Range(0, bin.Length / 8)
.Select(i => bin.Substring(8 * i, 8))
.Select(s => Convert.ToByte(s, 2))
.Select(b => b.ToString("x2"));
return String.Join(null, hex);
}
Using LINQ
string BinaryToHex(string binaryString)
{
var offset = 0;
StringBuilder sb = new();
while (offset < binaryString.Length)
{
var nibble = binaryString
.Skip(offset)
.Take(4);
sb.Append($"{Convert.ToUInt32(nibble.toString()), 2):X}");
offset += 4;
}
return sb.ToString();
}
You can take the input number four digit at a time. Convert this digit to ex ( as you did is ok ) then concat the string all together. So you obtain a string representing the number in hex, independetly from the size. Depending on where start MSB on your input string, may be the output string you obtain the way i described must be reversed.

Most light weight conversion from hex to byte in c#? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you convert Byte Array to Hexadecimal String, and vice versa?
I need an efficient and fast way to do this conversion. I have tried two different ways, but they are not efficient enough for me. Is there any other quick method to accomplish this in a real-time fashion for an application with huge data?
public byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length / 2).Select(x => Byte.Parse(hex.Substring(2 * x, 2), NumberStyles.HexNumber)).ToArray();
}
The above one felt more efficient to me.
public static byte[] stringTobyte(string hexString)
{
try
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
catch
{
throw;
}
If you really need efficiency then:
Don't create substrings
Don't create an iterator
Or, and get rid of try blocks which only have a catch block which rethrows... for simplicity rather than efficiency though.
This would be a pretty efficient version:
public static byte[] ParseHex(string hexString)
{
if ((hexString.Length & 1) != 0)
{
throw new ArgumentException("Input must have even number of characters");
}
int length = hexString.Length / 2;
byte[] ret = new byte[length];
for (int i = 0, j = 0; i < length; i++)
{
int high = ParseNybble(hexString[j++]);
int low = ParseNybble(hexString[j++]);
ret[i] = (byte) ((high << 4) | low);
}
return ret;
}
private static int ParseNybble(char c)
{
// TODO: Benchmark using if statements instead
switch (c)
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return c - '0';
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
return c - ('a' - 10);
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
return c - ('A' - 10);
default:
throw new ArgumentException("Invalid nybble: " + c);
}
return c;
}
The TODO refers to an alternative like this. I haven't measured which is faster.
private static int ParseNybble(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
c = (char) (c & ~0x20);
if (c >= 'A' && c <= 'F')
{
return c - ('A' - 10);
}
throw new ArgumentException("Invalid nybble: " + c);
}
I took the benchmarking code from the other question, and reworked it to test the hex to bytes methods given here:
HexToBytesJon: 36979.7 average ticks (over 150 runs)
HexToBytesJon2: 35886.4 average ticks (over 150 runs)
HexToBytesJonCiC: 31230.2 average ticks (over 150 runs)
HexToBytesJase: 15359.1 average ticks (over 150 runs)
HexToBytesJon is Jon's first version, and HexToBytesJon2 is the second variant.
HexToBytesJonCiC is Jon's version with CodesInChaos's suggested code.
HexToBytesJase is my attempt, based on both the above but with alternative nybble conversion which eschews error checking, and branching:
public static byte[] HexToBytesJase(string hexString)
{
if ((hexString.Length & 1) != 0)
{
throw new ArgumentException("Input must have even number of characters");
}
byte[] ret = new byte[hexString.Length/2];
for (int i = 0; i < ret.Length; i++)
{
int high = hexString[i*2];
int low = hexString[i*2+1];
high = (high & 0xf) + ((high & 0x40) >> 6) * 9;
low = (low & 0xf) + ((low & 0x40) >> 6) * 9;
ret[i] = (byte)((high << 4) | low);
}
return ret;
}
As a variant of Jon's if based ParseNybble:
public static byte[] ParseHex(string hexString)
{
if ((hexString.Length & 1) != 0)
{
throw new ArgumentException("Input must have even number of characters");
}
byte[] ret = new byte[hexString.Length / 2];
for (int i = 0; i < ret.Length; i++)
{
int high = ParseNybble(hexString[i*2]);
int low = ParseNybble(hexString[i*2+1]);
ret[i] = (byte) ((high << 4) | low);
}
return ret;
}
private static int ParseNybble(char c)
{
unchecked
{
uint i = (uint)(c - '0');
if(i < 10)
return (int)i;
i = ((uint)c & ~0x20u) - 'A';
if(i < 6)
return (int)i+10;
throw new ArgumentException("Invalid nybble: " + c);
}
}

How to Decode "=?utf-8?B?...?=" to string in C#

I use Visual Studio 2010, C# to read Gmail inbox using IMAP, it works as a charm, but I think Unicode is not fully supported as I cannot get Persian (Farsi) strings easily.
For instance I have my string: سلام, but IMAP gives me: "=?utf-8?B?2LPZhNin2YU=?=".
How can I convert it to original string? any tips from converting utf-8 to string?
Let's have a look at the meaning of the MIME encoding:
=?utf-8?B?...something...?=
^ ^
| +--- The bytes are Base64 encoded
|
+---- The string is UTF-8 encoded
So, to decode this, take the ...something... out of your string (2LPZhNin2YU= in your case) and then
reverse the Base64 encoding
var bytes = Convert.FromBase64String("2LPZhNin2YU=");
interpret the bytes as a UTF8 string
var text = Encoding.UTF8.GetString(bytes);
text should now contain the desired result.
A description of this format can be found in Wikipedia:
http://en.wikipedia.org/wiki/MIME#Encoded-Word
What you have is a MIME encoded string. .NET does not include libraries for MIME decoding, but you can either implement this yourself or use a library.
here he is
public static string Decode(string s)
{
return String.Join("", Regex.Matches(s ?? "", #"(?:=\?)([^\?]+)(?:\?B\?)([^\?]*)(?:\?=)").Cast<Match>().Select(m =>
{
string charset = m.Groups[1].Value;
string data = m.Groups[2].Value;
byte[] b = Convert.FromBase64String(data);
return Encoding.GetEncoding(charset).GetString(b);
}));
}
The following method decodes strings like "=?utf-8?B?..." or "=?utf-8?Q?..." into a normal string. The encoding (like "utf-8") is selected automatically. Regular expressions are not used. C#
public static string DecodeQuotedPrintables(string InputText)
{
var ResultChars = new List<char>();
Encoding encoding;
for (int i= 0; i < InputText.Length; i++)
{
var CurrentChar = InputText[i];
switch (CurrentChar)
{
case '=':
if((i + 1) < InputText.Length && InputText[i+1] == '?')
{
// Encoding
i += 2;
int StIndex = InputText.IndexOf('?', i);
int SubStringLength = StIndex - i;
string encodingName = InputText.Substring(i, SubStringLength);
encoding = Encoding.GetEncoding(encodingName);
i += SubStringLength + 1;
//Subencoding
StIndex = InputText.IndexOf('?', i);
SubStringLength = StIndex - i;
string SubEncoding = InputText.Substring(i, SubStringLength);
i += SubStringLength + 1;
//Text message
StIndex = InputText.IndexOf("?=", i);
SubStringLength = StIndex - i;
string Message = InputText.Substring(i, SubStringLength);
i += SubStringLength + 1;
// encoding
switch (SubEncoding)
{
case "B":
var base64EncodedBytes = Convert.FromBase64String(Message);
ResultChars.AddRange(encoding.GetString(base64EncodedBytes).ToCharArray());
// skip space #1
if ((i + 1) < InputText.Length && InputText[i + 1] == ' ')
{
i++;
}
break;
case "Q":
var CharByteList = new List<byte>();
for (int j = 0; j < Message.Length; j++)
{
var QChar = Message[j];
switch (QChar)
{
case '=':
j++;
string HexString = Message.Substring(j, 2);
byte CharByte = Convert.ToByte(HexString, 16);
CharByteList.Add(CharByte);
j += 1;
break;
default:
// Decode charbytes #1
if (CharByteList.Count > 0)
{
var CharString = encoding.GetString(CharByteList.ToArray());
ResultChars.AddRange(CharString.ToCharArray());
CharByteList.Clear();
}
ResultChars.Add(QChar);
break;
}
}
// Decode charbytes #2
if (CharByteList.Count > 0)
{
var CharString = encoding.GetString(CharByteList.ToArray());
ResultChars.AddRange(CharString.ToCharArray());
CharByteList.Clear();
}
// skip space #2
if ((i + 1) < InputText.Length && InputText[i + 1] == ' ')
{
i++;
}
break;
default:
throw new NotSupportedException($"Decode quoted printables: unsupported subencodeing: '{SubEncoding}'");
}
}
else
ResultChars.Add(CurrentChar);
break;
default:
ResultChars.Add(CurrentChar);
break;
}
}
return new string(ResultChars.ToArray());
}

Converting long string of binary to hex c#

I'm looking for a way to convert a long string of binary to a hex string.
the binary string looks something like this "0110011010010111001001110101011100110100001101101000011001010110001101101011"
I've tried using
hex = String.Format("{0:X2}", Convert.ToUInt64(hex, 2));
but that only works if the binary string fits into a Uint64 which if the string is long enough it won't.
is there another way to convert a string of binary into hex?
Thanks
I just knocked this up. Maybe you can use as a starting point...
public static string BinaryStringToHexString(string binary)
{
if (string.IsNullOrEmpty(binary))
return binary;
StringBuilder result = new StringBuilder(binary.Length / 8 + 1);
// TODO: check all 1's or 0's... throw otherwise
int mod4Len = binary.Length % 8;
if (mod4Len != 0)
{
// pad to length multiple of 8
binary = binary.PadLeft(((binary.Length / 8) + 1) * 8, '0');
}
for (int i = 0; i < binary.Length; i += 8)
{
string eightBits = binary.Substring(i, 8);
result.AppendFormat("{0:X2}", Convert.ToByte(eightBits, 2));
}
return result.ToString();
}
This might help you:
string HexConverted(string strBinary)
{
string strHex = Convert.ToInt32(strBinary,2).ToString("X");
return strHex;
}
Convert.ToInt32("1011", 2).ToString("X");
For string longer than this, you can simply break it into multiple bytes:
var binary = "0110011010010111001001110101011100110100001101101000011001010110001101101011";
var hex = string.Join(" ",
Enumerable.Range(0, binary.Length / 8)
.Select(i => Convert.ToByte(binary.Substring(i * 8, 8), 2).ToString("X2")));
I came up with this method. I am new to programming and C# but I hope you will appreciate it:
static string BinToHex(string bin)
{
StringBuilder binary = new StringBuilder(bin);
bool isNegative = false;
if (binary[0] == '-')
{
isNegative = true;
binary.Remove(0, 1);
}
for (int i = 0, length = binary.Length; i < (4 - length % 4) % 4; i++) //padding leading zeros
{
binary.Insert(0, '0');
}
StringBuilder hexadecimal = new StringBuilder();
StringBuilder word = new StringBuilder("0000");
for (int i = 0; i < binary.Length; i += 4)
{
for (int j = i; j < i + 4; j++)
{
word[j % 4] = binary[j];
}
switch (word.ToString())
{
case "0000": hexadecimal.Append('0'); break;
case "0001": hexadecimal.Append('1'); break;
case "0010": hexadecimal.Append('2'); break;
case "0011": hexadecimal.Append('3'); break;
case "0100": hexadecimal.Append('4'); break;
case "0101": hexadecimal.Append('5'); break;
case "0110": hexadecimal.Append('6'); break;
case "0111": hexadecimal.Append('7'); break;
case "1000": hexadecimal.Append('8'); break;
case "1001": hexadecimal.Append('9'); break;
case "1010": hexadecimal.Append('A'); break;
case "1011": hexadecimal.Append('B'); break;
case "1100": hexadecimal.Append('C'); break;
case "1101": hexadecimal.Append('D'); break;
case "1110": hexadecimal.Append('E'); break;
case "1111": hexadecimal.Append('F'); break;
default:
return "Invalid number";
}
}
if (isNegative)
{
hexadecimal.Insert(0, '-');
}
return hexadecimal.ToString();
}
Considering four bits can be expressed by one hex value, you can simply go by groups of four and convert them seperately, the value won't change that way.
string bin = "11110110";
int rest = bin.Length % 4;
if(rest != 0)
bin = new string('0', 4-rest) + bin; //pad the length out to by divideable by 4
string output = "";
for(int i = 0; i <= bin.Length - 4; i +=4)
{
output += string.Format("{0:X}", Convert.ToByte(bin.Substring(i, 4), 2));
}
If you want to iterate over the hexadecimal representation of each byte in the string, you could use the following extension. I've combined Mitch's answer with this.
static class StringExtensions
{
public static IEnumerable<string> ToHex(this String s) {
if (s == null)
throw new ArgumentNullException("s");
int mod4Len = s.Length % 8;
if (mod4Len != 0)
{
// pad to length multiple of 8
s = s.PadLeft(((s.Length / 8) + 1) * 8, '0');
}
int numBitsInByte = 8;
for (var i = 0; i < s.Length; i += numBitsInByte)
{
string eightBits = s.Substring(i, numBitsInByte);
yield return string.Format("{0:X2}", Convert.ToByte(eightBits, 2));
}
}
}
Example:
string test = "0110011010010111001001110101011100110100001101101000011001010110001101101011";
foreach (var hexVal in test.ToHex())
{
Console.WriteLine(hexVal);
}
Prints
06
69
72
75
73
43
68
65
63
6B
If you're using .NET 4.0 or later and if you're willing to use System.Numerics.dll (for BigInteger class), the following solution works fine:
public static string ConvertBigBinaryToHex(string bigBinary)
{
BigInteger bigInt = BigInteger.Zero;
int exponent = 0;
for (int i = bigBinary.Length - 1; i >= 0; i--, exponent++)
{
if (bigBinary[i] == '1')
bigInt += BigInteger.Pow(2, exponent);
}
return bigInt.ToString("X");
}
Considering four bits can be expressed by one hex value, you can simply go by groups of four and convert them seperately, the value won't change that way.
string bin = "11110110";
int rest = bin.Length % 4;
bin = bin.PadLeft(rest, '0'); //pad the length out to by divideable by 4
string output = "";
for(int i = 0; i <= bin.Length - 4; i +=4)
{
output += string.Format("{0:X}", Convert.ToByte(bin.Substring(i, 4), 2));
}
static string BinToHex(string bin)
{
if (bin == null)
throw new ArgumentNullException("bin");
if (bin.Length % 8 != 0)
throw new ArgumentException("The length must be a multiple of 8", "bin");
var hex = Enumerable.Range(0, bin.Length / 8)
.Select(i => bin.Substring(8 * i, 8))
.Select(s => Convert.ToByte(s, 2))
.Select(b => b.ToString("x2"));
return String.Join(null, hex);
}
Using LINQ
string BinaryToHex(string binaryString)
{
var offset = 0;
StringBuilder sb = new();
while (offset < binaryString.Length)
{
var nibble = binaryString
.Skip(offset)
.Take(4);
sb.Append($"{Convert.ToUInt32(nibble.toString()), 2):X}");
offset += 4;
}
return sb.ToString();
}
You can take the input number four digit at a time. Convert this digit to ex ( as you did is ok ) then concat the string all together. So you obtain a string representing the number in hex, independetly from the size. Depending on where start MSB on your input string, may be the output string you obtain the way i described must be reversed.

How to convert hex to a byte array?

I copied and pasted this binary data out of sql server, which I am unable to query at this time.
0xBAC893CAB8B7FE03C927417A2A3F6A60BD30FF35E250011CB25507EBFCD5223B
How do I convert it back to a byte array in c#?
Something like this:
using System;
public static class Parser
{
static void Main()
{
string hex = "0xBAC893CAB8B7FE03C927417A2A3F6A6"
+ "0BD30FF35E250011CB25507EBFCD5223B";
byte[] parsed = ParseHex(hex);
// Just for confirmation...
Console.WriteLine(BitConverter.ToString(parsed));
}
public static byte[] ParseHex(string hex)
{
int offset = hex.StartsWith("0x") ? 2 : 0;
if ((hex.Length % 2) != 0)
{
throw new ArgumentException("Invalid length: " + hex.Length);
}
byte[] ret = new byte[(hex.Length-offset)/2];
for (int i=0; i < ret.Length; i++)
{
ret[i] = (byte) ((ParseNybble(hex[offset]) << 4)
| ParseNybble(hex[offset+1]));
offset += 2;
}
return ret;
}
static int ParseNybble(char c)
{
if (c >= '0' && c <= '9')
{
return c-'0';
}
if (c >= 'A' && c <= 'F')
{
return c-'A'+10;
}
if (c >= 'a' && c <= 'f')
{
return c-'a'+10;
}
throw new ArgumentException("Invalid hex digit: " + c);
}
}
(EDIT: Now slightly more efficient - no substrings required...)
It's possible that ParseNybble could be more efficient. For example, a switch/case may be more efficient:
static int ParseNybble(char c)
{
switch (c)
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return c-'0';
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
return c-'A'+10;
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
return c-'a'+10;
}
throw new ArgumentException("Invalid hex digit: " + c);
}
or possibly a lookup array:
// Omitted for brevity... I'm sure you get the gist
private static readonly int[] NybbleLookup = BuildLookup();
private int ParseNybble(char c)
{
if (c > 'f')
{
throw new ArgumentException("Invalid hex digit: " + c);
}
int ret = NybbleLookup[c];
if (ret == -1)
{
throw new ArgumentException("Invalid hex digit: " + c);
}
return ret;
}
I haven't benchmarked any of these, and I've no idea which would be the fastest. The current solution is probably the simplest though.
Consider leveraging a Framework class that already exposes the ability to perform hex conversion, XmlReader for example:
public static byte[] HexToBytes(this string hexEncodedBytes, int start, int end)
{
int length = end - start;
const string tagName = "hex";
string fakeXmlDocument = String.Format("<{1}>{0}</{1}>",
hexEncodedBytes.Substring(start, length),
tagName);
var stream = new MemoryStream(Encoding.ASCII.GetBytes(fakeXmlDocument));
XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings());
int hexLength = length / 2;
byte[] result = new byte[hexLength];
reader.ReadStartElement(tagName);
reader.ReadContentAsBinHex(result, 0, hexLength);
return result;
}
usage:
string input = "0xBAC893CAB8B7FE03C927417A2A3F6A60BD30FF35E250011CB255";
byte[] bytes = input.HexToBytes(2, input.Length);
Simple:
string hexnum = "0000000F"; // Represents 15
int value = int.Parse(hexnum, System.Globalization.NumberStyles.HexNumber);
All you have to remember to do is for an int to divide the hex number up into groups of 8 hex digits (hex are 4 bits each, and CLR int type is 32 bits, hence 8 digits per int). There's also a byte.Parse() that works the same, but pass in two hex digits at a time.
Something like this:
public byte[] ParseHexString(string text)
{
if ((text.Length % 2) != 0)
{
throw new ArgumentException("Invalid length: " + text.Length);
}
if (text.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase))
{
text = text.Substring(2);
}
int arrayLength = text.Length / 2;
byte[] byteArray = new byte[arrayLength];
for (int i = 0; i < arrayLength; i++)
{
byteArray[i] = byte.Parse(text.Substring(i*2, 2), NumberStyles.HexNumber);
}
return byteArray;
}
You will need to modify this a little bit (for example, skip over the first two characters), but it does handle spaces in the string:
/// <summary>
/// Decodes a hex string, ignoring all non-hex characters, and stores
/// the decodes series of bytes into the shared buffer. This returns
/// the number of bytes that were decoded.
/// <para>Hex characters are [0-9, a-f, A-F].</para>
/// </summary>
/// <param name="hexString">String to parse into bytes.</param>
/// <param name="buffer">Buffer into which to store the decoded binary data.</param>
/// <returns>The number of bytes decoded.</returns>
private static int DecodeHexIntoBuffer(string hexString, byte[] buffer)
{
int count = 0;
bool haveFirst = false;
bool haveSecond = false;
char first = '0';
char second = '0';
for (int i = 0; i < hexString.Length; i++)
{
if (!haveFirst)
{
first = hexString[i];
haveFirst = char.IsLetterOrDigit(first);
// we have to continue to the next iteration
// or we will miss characters
continue;
}
if (!haveSecond)
{
second = hexString[i];
haveSecond = char.IsLetterOrDigit(second);
}
if (haveFirst && haveSecond)
{
string hex = "" + first + second;
byte nextByte;
if (byte.TryParse(hex, NumberStyles.HexNumber, null, out nextByte))
{
// store the decoded byte into the next slot of the buffer
buffer[count++] = nextByte;
}
// reset the flags
haveFirst = haveSecond = false;
}
}
return count;
}
Actually, there's an easier way to convert two characters at a time to a byte:
/// <summary>
/// This will convert a hex-encoded string to byte data
/// </summary>
/// <param name="hexData">The hex-encoded string to convert</param>
/// <returns>The bytes that make up the hex string</returns>
public static byte[] FromHex(string hexData)
{
List<byte> data = new List<byte>();
string byteSet = string.Empty;
int stringLen = hexData.Length;
int length = 0;
for (int i = 0; i < stringLen; i = i + 2)
{
length = (stringLen - i) > 1 ? 2 : 1;
byteSet = hexData.Substring(i, length);
// try and parse the data
data.Add(Convert.ToByte(byteSet, 16 /*base*/));
} // next set
return data.ToArray();
}
Slow yet fun way :D
public static byte[] StringToByteArray(string hex)
{
hex = hex.Replace(" ", "");
hex = hex.Replace(":", "");
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
-jD
I use this for C#, from similar code in Java.
private static char[] hexdigit = "0123456789abcdef".ToCharArray();
public static string hexlify(string argbuf) {
int arglen = argbuf.Length;
char[] argca = argbuf.ToCharArray ();
StringBuilder retbuf = new StringBuilder(arglen * 2);
for (int i = 0; i < arglen; i++) {
char ch = argca[i];
retbuf.Append(hexdigit[(ch >> 4) & 0xF]);
retbuf.Append(hexdigit[ch & 0xF]);
}
return retbuf.ToString();
}
public static string unhexlify(string argbuf) {
int arglen = argbuf.Length;
if (arglen % 2 != 0) {
throw new ArgumentOutOfRangeException ("Odd-length string");
}
char[] argca = argbuf.ToCharArray ();
StringBuilder retbuf = new StringBuilder(arglen / 2);
for (int i = 0; i < arglen; i += 2) {
int top = Convert.ToInt32 (argca[i].ToString (), 16);
int bot = Convert.ToInt32 (argca[i + 1].ToString (), 16);
if (top == -1 || bot == -1) {
throw new ArgumentOutOfRangeException ("Non-hexadecimal digit found");
}
retbuf.Append((char) ((top << 4) + bot));
}
return retbuf.ToString();
}
maybe this one is cute!
string source = "Hello World!";
using (SHA256 sha256Hash = SHA256.Create())
{
//From String to byte array
byte[] sourceBytes = Encoding.UTF8.GetBytes(source);
byte[] hashBytes = sha256Hash.ComputeHash(sourceBytes);
string hash = BitConverter.ToString(hashBytes).Replace("-", String.Empty);
Console.WriteLine("The SHA256 hash of " + source + " is: " + hash);
}

Categories

Resources