How do I convert a Hexidecimal string to byte in C#? - c#

How can I convert this string into a byte?
string a = "0x2B";
I tried this code, (byte)(a); but it said:
Cannot convert type string to byte...
And when I tried this code, Convert.ToByte(a); and this byte.Parse(a);, it said:
Input string was not in a correct format...
What is the proper code for this?
But when I am declaring it for example in an array, it is acceptable...
For example:
byte[] d = new byte[1] = {0x2a};

You have to specify the base to use in Convert.ToByte since your input string contains a hex number:
byte b = Convert.ToByte(a, 16);

byte b = Convert.ToByte(a, 16);

You can use the ToByte function of the Convert helper class:
byte b = Convert.ToByte(a, 16);

Update:
As others have mentioned, my original suggestion to use byte.Parse() with NumberStyles.HexNumber actually won't work with hex strings with "0x" prefix. The best solution is to use Convert.ToByte(a, 16) as suggested in other answers.
Original answer:
Try using the following:
byte b = byte.Parse(a, NumberStyles.HexNumber, CultureInfo.InvariantCulture);

You can use UTF8Encoding:
public static byte[] StrToByteArray(string str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}

Related

How to convert a byteArray to Binary Value in c#?

I initilaly have a string which is converted to byteArray.
Then I convert this byteArray to HEX as shown below in my code.
Then I further need to convert this to a binary value.
string ID = "A0101185K";
byte[] ba = Encoding.Default.GetBytes(IC);
var hexString= BitConverter.ToString(ba).Replace("-", "");
You can convert byte to string in that way
static string ToBinary(byte b) => Convert.ToString(b, 2).PadLeft(8, '0');
and use it in your program like this
string MESSAGE = "A0101185K";
byte[] bytes = Encoding.Default.GetBytes(MESSAGE);
var binaries = string.Concat(bytes.Select(ToBinary));
I hope that helps you. But of course you didn't tell how you want to store your result, so maybe this is not the right answer.

how to deocde some coded text in c# [duplicate]

I have following string as utf-8. i want convert it to persian unicode:
ابراز داشت: امام رضا برخال� دیگر ائمه با جنگ نرم
this site correctly do convert and result is: ابراز داشت: امام رضا برخالف دیگر ائمه با جنگ نرم
I test many method and ways but can't resolve this problem, for example these two lines did not produce the desired result:
string result = Encoding.GetEncoding("all type").GetString(input);
and
byte[] preambleBytes= Encoding.UTF8.GetPreamble();
byte[] inputBytes= Encoding.UTF8.GetBytes(input);
byte[] resultBytes= preambleBytes.Concat(inputBytes).ToArray();
string result=Encoding.UTF8.GetString(resultBytes.ToArray());
string resultAscii=Encoding.Ascii.GetString(inputBytes);
string resultUnicode=Encoding.Unicode.GetString(inputBytes);
You can use Encoding.Convert.
string source = // Your source
byte[] utfb = Encoding.UTF8.GetBytes(source);
byte[] resb = Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding("ISO-8859-6"), utfb);
string result = Encoding.GetEncoding("ISO-8859-6").GetString(resb);
NOTE: I wasn't sure which standard you wanted so for the example I used ISO-8859-6 (Arabic).
I understand what is problem by reading What is problem and Solution .
when i converted string to byte[], i forced that to convert as utf-8 format but really i should use default format for converting.
False converting:
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
resultString = Encoding.UTF8.GetString(bytes);
But
True converting:
byte[] bytes = Encoding.Default.GetBytes(inputString);
resultString = Encoding.UTF8.GetString(bytes);
Tanks for your comments and answers.
I get bytes by UTF8 and Get String by Default as follow. This worked for me.
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
resultString = Encoding.Default.GetString(bytes);

Set the value of a new byte using a string?

I have a string with a numerical value that will fit into a data type byte variable (e.g. "243").
I want to set the byte to the numerical value of the string, something similar to byte myByte = 243; but using the string instead. How would this be possible?
Use byte.Parse() method:
byte myByte = byte.Parse("243");
You can do something like this
string myString = "243";
var byteData = Convert.ToByte(myString);
You can use this to convert your string value to byte:
byte MyByte = Convert.ToByte("243");

How to convert Hex to Chinese ASCII character in c#? [duplicate]

I have the following code to convert from HEX to ASCII.
//Hexadecimal to ASCII Convertion
private static string hex2ascii(string hexString)
{
MessageBox.Show(hexString);
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= hexString.Length - 2; i += 2)
{
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
return sb.ToString();
}
input hexString = D3FCC4A7B6FABBB7
output return = Óüħ¶ú»·
The output that I need is 狱魔耳环, but I am getting Óüħ¶ú»· instead.
How would I make it display the correct string?
First, convert the hex string to a byte[], e.g. using code at How do you convert Byte Array to Hexadecimal String, and vice versa?. Then use System.Text.Encoding.Unicode.GetString(myArray) (use proper encoding, might not be Unicode, but judging from your example it is a 16-bit encoding, which, incidentally, is not "ASCII", which is 7-bit) to convert it to a string.

Converting a md5 hash byte array to a string

How can I convert the hashed result, which is a byte array, to a string?
byte[] bytePassword = Encoding.UTF8.GetBytes(password);
using (MD5 md5 = MD5.Create())
{
byte[] byteHashedPassword = md5.ComputeHash(bytePassword);
}
I need to convert byteHashedPassword to a string.
public static string ToHex(this byte[] bytes, bool upperCase)
{
StringBuilder result = new StringBuilder(bytes.Length*2);
for (int i = 0; i < bytes.Length; i++)
result.Append(bytes[i].ToString(upperCase ? "X2" : "x2"));
return result.ToString();
}
You can then call it as an extension method:
string hexString = byteArray.ToHex(false);
I always found this to be the most convenient:
string hashPassword = BitConverter.ToString(byteHashedPassword).Replace("-","");
For some odd reason BitConverter likes to put dashes between bytes, so the replace just removes them.
Update:
If you prefer "lowercase" hex, just do a .ToLower() and boom.
Do note that if you are doing this as a tight loop and many ops this could be expensive since there are at least two implicit string casts and resizes going on.
You can use Convert.ToBase64String and Convert.FromBase64String to easily convert byte arrays into strings.
If you're in the 'Hex preference' camp you can do this. This is basically a minimal version of the answer by Philippe Leybaert.
string.Concat(hash.Select(x => x.ToString("X2")))
B1DB2CC0BAEE67EA47CFAEDBF2D747DF
Well as it is a hash, it has possibly values that cannot be shown in a normal string, so the best bet is to convert it to Base64 encoded string.
string s = Convert.ToBase64String(bytes);
and use
byte[] bytes = Convert.FromBase64(s);
to get the bytes back.
Well, you could use the string constructor that takes bytes and an encoding, but you'll likely get a difficult to manage string out of that since it could contain lots of fun characters (null bytes, newlines, control chars, etc)
The best way to do this would be to encode it with base 64 to get a nice string that's easy to work with:
string s = Convert.ToBase64String(bytes);
And to go from that string back to a byte array:
byte[] bytes = Convert.FromBase64String(s);
I know this is an old question, but I thought I would add you can use the built-in methods (I'm using .NET 6.0):
Convert.ToBase64String(hashBytes); (Others have already mentioned this)
Convert.ToHexString(hashBytes);
For anyone interested a Nuget package I created called CryptoStringify allows you to convert a string to a hashed string using a nice clean syntax, without having to play around with byte arrays:
using (MD5 md5 = MD5.Create())
{
string strHashedPassword = md5.Hash(password);
}
It's an extension method on HashAlgorithm and KeyedHashAlgorithm so works on SHA1, HMACSHA1, SHA256 etc too.
https://www.nuget.org/packages/cryptostringify

Categories