I'm trying to convert an unHex value to a string but it's not working.
I have the following value 0x01BB92E7F716F55B144768FCB2EA40187AE6CF6B2E52A64F7331D0539507441F7D770112510D679F0B310116B0D709E049A19467672FFA532A7C30DFB72
Result I hope would be this
but executing the function below displays this result
»’ Ç ÷ õ [Ghü²ê # zæÏk.R¦Os1ÐS • D} w Q gŸ 1 ° × àI¡ ”gg / úS * | 0ß ·) = ¤
Any idea how I can extract the information as expected
public static string Hex2String (string input)
{
var builder = new StringBuilder ();
for (int i = 0; i < socketLength; i + = 2)
{
// throws an exception if not properly formatted
string hexdec = input.Substring (i, 2);
int number = Int32.Parse (hexdec, NumberStyles.HexNumber);
char charToAdd = (char) number;
builder.Append (charToAdd);
}
return builder.ToString ();
}
Your result is base64-encoded. Base64 is a way of taking a byte array and turning it into human-readable characters.
Your code tries to take these raw bytes and cast them to chars, but not all byte values are valid printable characters: some are control characters, some can't be printed, etc.
Instead, let's turn the hex string into a byte array, and then turn that byte array into a base64 string.
string input = "01BB92E7F716F55B144768FCB2EA40187AE6CF6B2E52A64F7331D0539507441F7D770112510D679F0B310116B0D709E049A19467672FFA532A7C30DFB72";
byte[] bytes = new byte[input.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = byte.Parse(input.Substring(i * 2, 2), NumberStyles.HexNumber);
}
string result = Convert.ToBase64String(bytes);
This results in:
AbuS5/cW9VsUR2j8supAGHrmz2suUqZPczHQU5UHRB99dwESUQ1nnwsxARaw1wngSaGUZ2cv+lMqfDDftw==
See it running here.
Related
I have a String like this:
String data = "0x0f";
and I would like to leave it as a single byte which represents this hex. Does anyone know what function I can use?
I tried using the following function:
public byte pegarValorHexText(string text)
{
int NumberChars = text.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(text.Substring(i, 2), 16);
return bytes[0];
}
The string has a hexadecimal value, it has a maximum of 4 characters, the sequence "0x" indicating that it is a hexadecimal value and a sequence of two hex chars
Just use Convert.ToByte then, it should handle the hex prefix:
byte b = Convert.ToByte("0x0f", 16); // 15
I have a string of hex that I want to convert to UTF-16L, as specified at https://en.wikipedia.org/wiki/GUID_Partition_Table under "Partition entries (LBA 2–33)". The string with hex has a fixed length of 72 bytes. I'm not sure what to do to convert it. I was thinking converting it to byte first then use Encoding.BigEndianUnicode Property.
Also when I tried to use Encoding.UTF8.GetChars then I got a lot of spaces in my result.
static void Main(string[] args)
{
string hexString = "4200610073006900630020006400610074006100200070006100720074006900740069006F006E000000000000000000000000000000000000000000000000000000000000000000";
int length = hexString.Length;
byte[] bytes = new byte[length / 2];
for (int i = 0; i < length; i += 2){
bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
}
char[] chars = Encoding.UTF8.GetChars(bytes);
string s = new string(chars);
Console.WriteLine(s);
}
Prints this:
B a s i c d a t a p a r t i t i o n
(B\0a\0s\0i\0c\0 \0d\0a\0t\0a\0 \0p\0a\0r\0t\0i\0t\0i\0o\0n\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0)
So I am creating a program that reads a byte array and returns the value
byte[] buffer1 = File.ReadAllBytes(path).Skip(startPos).Take(lengthToExtract).ToArray();
byte[] reversed = buffer1.Reverse().ToArray();
string buffer2 = "";
foreach (var i in reversed)
{
buffer2 = buffer2 + i.ToString("X") + " ";
}
MessageBox.Show(buffer2);
int size = int.Parse(buffer2.Replace(" ", string.Empty), System.Globalization.NumberStyles.HexNumber);
return size;
But when I get the message box for the value of the hex string buffer of the values it takes out the "unimportant" hex number out which messes up my value. For example if the byte read is 0x00 it will return the value as just 0, and I am reading the resulted bytes backwards so: 0x04080 (0 4 0 80) is different then 0x0040080 (00 04 00 80). I need help please this messes up my entire program.
Here are 2 functions you can use. They will solve both of the problems - double digits and bytes order
public static string HexStringFromArrayChangeEndian(byte[] data)
{
StringBuilder sdata = new StringBuilder();
for (int s = data.Length - 1; s >= 0; s--)
sdata.Append(string.Format("{0:X}", data[s]).PadLeft(2, '0'));
return sdata.ToString();
}
public static string HexStringFromArraySameEndian(byte[] data)
{
StringBuilder sdata = new StringBuilder();
for (int s = 0; s < data.Length; s++)
sdata.Append(string.Format("{0:X}", data[s]).PadLeft(2, '0'));
return sdata.ToString();
}
Use i.ToString("X2"). Will force string output of "00" instead of simplified "0"
I am trying to convert a hexadecimal values in a string in to both ASCII value and UTF8 value. But when I execute the following code, it prints out the same hex value I give as input
string hexString = "68656c6c6f2c206d79206e616d6520697320796f752e";
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
byte[] dBytes = encoding.GetBytes(hexString);
//To get ASCII value of the hex string.
string ASCIIresult = System.Text.Encoding.ASCII.GetString(dBytes);
MessageBox.Show(ASCIIresult, "Showing value in ASCII");
//To get the UTF8 value of the hex string
string utf8result = System.Text.Encoding.UTF8.GetString(dBytes);
MessageBox.Show(utf8result, "Showing value in UTF8");
Since you are naming a variable hexString, I assume that the value is already encoded into a hex format.
This means the following will not work:
string hexString = "68656c6c6f2c206d79206e616d6520697320796f752e";
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
byte[] dBytes = encoding.GetBytes(hexString);
This is because you are treating the already encoded string as plain UTF8 text.
You are probably missing a step to convert the hex encoded string into a byte array.
You can do this using this SO post which shows this function:
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length/2;
byte[] bytes = new byte[NumberChars];
using (var 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);
}
return bytes;
}
So, the end result would be this:
byte[] dBytes = StringToByteArray(hexString);
//To get ASCII value of the hex string.
string ASCIIresult = System.Text.Encoding.ASCII.GetString(dBytes);
MessageBox.Show(ASCIIresult, "Showing value in ASCII");
//To get the UTF8 value of the hex string
string utf8result = System.Text.Encoding.UTF8.GetString(dBytes);
MessageBox.Show(utf8result, "Showing value in UTF8");
You should first convert the hex string to a byte array:
byte[] dBytes = Enumerable.Range(0, hexString.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
.ToArray();
I've used this method to convert any
public static string FromHex (string h) //Put your sequence of hex to convert to string.
{
if (h.Length % 2 != 0)
throw new ArgumentException("The string " + nameof(h) + " is not a valid Hex.", nameof(h));
char[] CharFromHex = new char[h.Length / 2];
int j = 0;
for (int i = 0; i < h.Length; i += 2)
{
string hexSubStr = h.Substring(i, 2);
CharFromHex[j] = (char)Convert.ToInt32(hexSubStr, 16);
j += 1;
}
StringBuilder str = new StringBuilder();
str.Append(CharFromHex);
return str.ToString();
}
I have the following code:
using (BinaryReader br = new BinaryReader(
File.Open(FILE_PATH, FileMode.Open, FileAccess.ReadWrite)))
{
int pos = 0;
int length = (int) br.BaseStream.Length;
while (pos < length)
{
b[pos] = br.ReadByte();
pos++;
}
pos = 0;
while (pos < length)
{
Console.WriteLine(Convert.ToString(b[pos]));
pos++;
}
}
The FILE_PATH is a const string that contains the path to the binary file being read.
The binary file is a mixture of integers and characters.
The integers are 1 bytes each and each character is written to the file as 2 bytes.
For example, the file has the following data :
1HELLO HOW ARE YOU45YOU ARE LOOKING GREAT //and so on
Please note: Each integer is associated with the string of characters following it. So 1 is associated with "HELLO HOW ARE YOU" and 45 with "YOU ARE LOOKING GREAT" and so on.
Now the binary is written (I do not know why but I have to live with this) such that '1' will take only 1 byte while 'H' (and other characters) take 2 bytes each.
So here is what the file actually contains:
0100480045..and so on
Heres the breakdown:
01 is the first byte for the integer 1
0048 are the 2 bytes for 'H' (H is 48 in Hex)
0045 are the 2 bytes for 'E' (E = 0x45)
and so on..
I want my Console to print human readable format out of this file: That I want it to print "1 HELLO HOW ARE YOU" and then "45 YOU ARE LOOKING GREAT" and so on...
Is what I am doing correct? Is there an easier/efficient way?
My line Console.WriteLine(Convert.ToString(b[pos])); does nothing but prints the integer value and not the actual character I want. It is OK for integers in the file but then how do I read out characters?
Any help would be much appreciated.
Thanks
I think what you are looking for is Encoding.GetString.
Since your string data is composed of 2 byte characters, how you can get your string out is:
for (int i = 0; i < b.Length; i++)
{
byte curByte = b[i];
// Assuming that the first byte of a 2-byte character sequence will be 0
if (curByte != 0)
{
// This is a 1 byte number
Console.WriteLine(Convert.ToString(curByte));
}
else
{
// This is a 2 byte character. Print it out.
Console.WriteLine(Encoding.Unicode.GetString(b, i, 2));
// We consumed the next character as well, no need to deal with it
// in the next round of the loop.
i++;
}
}
You can use String System.Text.UnicodeEncoding.GetString() which takes a byte[] array and produces a string.
I found this link very useful
Note that this is not the same as just blindly copying the bytes from the byte[] array into a hunk of memory and calling it a string. The GetString() method must validate the bytes and forbid invalid surrogates, for example.
using (BinaryReader br = new BinaryReader(File.Open(FILE_PATH, FileMode.Open, FileAccess.ReadWrite)))
{
int length = (int)br.BaseStream.Length;
byte[] buffer = new byte[length * 2];
int bufferPosition = 0;
while (pos < length)
{
byte b = br.ReadByte();
if(b < 10)
{
buffer[bufferPosition] = 0;
buffer[bufferPosition + 1] = b + 0x30;
pos++;
}
else
{
buffer[bufferPosition] = b;
buffer[bufferPosition + 1] = br.ReadByte();
pos += 2;
}
bufferPosition += 2;
}
Console.WriteLine(System.Text.Encoding.Unicode.GetString(buffer, 0, bufferPosition));
}