This question already has answers here:
How do you convert a byte array to a hexadecimal string, and vice versa?
(53 answers)
Converting string to byte array in C#
(20 answers)
Closed 2 years ago.
I need to cast a string to a byte array in hex representation.
For example:
Value: 06000002
What I need is:
30 36 30 30 30 30 30 32
I tried to implicit convert all chars to byte as following:
byte[] bytes = new byte[daten.Length];
for (int i = 0; i < daten.Length; i++)
{
int value = Convert.ToInt32(daten[i]);
bytes[i] = (byte)daten[i];
}
However I always get this result:
48 54 48 48 48 48 48 50
I do not need the result as string! I need it as byte array!
How do achive this?
All you should need is:
var value = "06000002";
byte[] bytes = Encoding.UTF8.GetBytes(value);
In .NET 5 you can then use
string hexString = Convert.ToHexString(bytes);
To verify your result is what you expected
3036303030303032
https://dotnetfiddle.net/6sUmgE
To get the desired output, you can convert each character to its hex representation:
var s = "06000002";
var bytes = s.Select(c => (byte) c);
var hexCodes = bytes.Select(b => b.ToString("X2"));
You could stop here, or perhaps convert it to an Array or List.
Note that bytes are just numbers, there is no such thing as "hex bytes". The only time where "hex" exists is after conversion to string format, as I did above.
To still get it as one string you can proceed with this:
var result = string.Join(' ', hexCodes);
Or all in one go:
var result = string.Join(' ', "06000002".Select(c => ((byte) c).ToString("X2")));
Related
I would like to ask a question about string convert to byte from windows form, i have try several ways to do these, while convert string to hex is successful turn to string but the problem i need to turn it back to hex byte because the API only get bytes.
Here is the convert below:
string getTxtString = txtString.text;
int convertToInt = int32.Parse(getTxtString);
string hexString = convertToInt.toString("X");
// i have try with X2 it will get two digit for example 0A
How to convert to Hex byte in situation like this or please provide other solution.
For example:
11 = 0A
0A is the conversion of below:
int convertToInt = int32.Parse(getTxtString);
string hexString = convertToInt.toString("X2");
From the convert above will only get 0A.
The Api need to whole Hex value like 0x0A, i need to send 0x0A to API.
Try Convert.ToByte while providing fromBase (16 in your case)
// "0A" (string) -> 0x0A == 10 == 0b00001010 (byte)
byte result = Convert.ToByte(hexString, 16);
...
SomeApiMethod(..., result, ...);
In case you have a Int32 encoded in fact (e.g. "FF120A") and you want to get the last byte:
// "FF120A" (or "0xFF120A") -> 0xFF120A (int) -> 0x0A (byte)
// unchecked - we don't want OverflowException on integer overflow
byte result = unchecked((byte)Convert.ToInt32(hexString, 16));
...
SomeApiMethod(..., result, ...);
Please, notice that the byte (e.g. 0x0A) is always the same, it its string representation that can vary:
// 00001010 - binary
Console.WriteLine(Convert.ToString(result, 2).PadLeft(8, '0'));
// 10 - decimal
Console.WriteLine(result);
// 0A - hexadecimal
Console.WriteLine(result.ToString("X2"));
I'm trying to convert from a Base64 string. First I tried this:
string a = "BTQmJiI6JzFkZ2ZhY";
byte[] b = Convert.FromBase64String(a);
string c = System.Text.Encoding.ASCII.GetString(b);
Then got the exception - System.FormatException was caught Message=Invalid length for a Base-64 char array.
So after googling,I tried this:
string a1 = "BTQmJiI6JzFkZ2ZhY";
int mod4 = a1.Length % 4;
if (mod4 > 0)
{
a1 += new string('=', 4 - mod4);
}
byte[] b1 = Convert.FromBase64String(a1);
string c1 = System.Text.Encoding.ASCII.GetString(b1);
Here I got the exception - System.FormatException was caught Message=Invalid character in a Base-64 string.
Is there any invalid character in "BTQmJiI6JzFkZ2ZhY"? Or is it the length issue?
EDIT: I first decrypt the input string using the below code:
string sourstr, deststr,strchar;
int strlen;
decimal ascvalue, ConvValue;
deststr = "";
sourstr = "InputString";
strlen = sourstr.Length;
for (int intI = 0; intI <= strlen - 1; intI++)
{
strchar = sourstr.Substring(intI, 1);
ascvalue = (decimal)strchar[0];
ConvValue = (decimal)((int)ascvalue ^ 85);
if ((char)ConvValue.ToString().Length == 0)
{
deststr = deststr + strchar;
}
else
{
deststr = deststr + (char)ConvValue;
}
}
This output deststr is passed to below code
Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(deststr));
This is where I got "BTQmJiI6JzFkZ2ZhY"
You cannot get such base64 string by encoding whole number of bytes. While encoding, every 3 bytes are represented as 4 characters, because 3 bytes is 24 bits, and each base64 character is 6 bits (2^6=64), so 4 of them is also 24 bits. If number of bytes to encode is not divisable by 3 - you have some bytes left. You can have 2 or 1 bytes left.
If you have 2 bytes left - that's 16 bits and you need at least 3 characters to encode that (2 characters is just 12 bits - not enough). So in case you have 2 bytes left - you encode them with 3 characters and apply "=" padding.
If you have 1 byte left - that's 8 bits. You need at least 2 characters for that. You encode to 2 characters and apply "==" padding.
Note that there is no way to encode something to just one character (and for that reason - there is no "===" padding).
Your string can be divided in 4 character blocks: "BTQm", "JiI6", "JzFk", "Z2Zh", "Y". 4 first blocks each represent 3 bytes, but what "Y" represents? Who knows. You can say that it represents 1 byte in range 0-63, but from above you can see that's not how it works, so to interpret it like that you have to do it yourself.
From above you can see that you cannot get base64 string with length 17 (without padding). You can get 16, 18, 19, 20, but never 17
Are you sure you took all chars from base64 output?
Appending "==" at the end of the string will make your first approach work without any problems. Although there is strange character at the beginning of the output. So the next question is: Are you sure it is "ASCI" Encoding?
This question already has answers here:
Convert int to a bit array in .NET
(10 answers)
Closed 7 years ago.
I want to convert my base 10 number to base 2 and then store parts in an array.
Here are two examples:
my value is 5 so it will be converted to 101 then I have an array like this: {1,0,1}
or my value is 26 so it will be converted to 11010 then I will have an array like this: {0,1,0,1,1}
Thank you in advance for your time and consideration.
To convert the int 'x'
int x = 3;
One way, by manipulation on the int :
string s = Convert.ToString(x, 2); //Convert to binary in a string
int[] bits= s.PadLeft(8, '0') // Add 0's from left
.Select(c => int.Parse(c.ToString())) // convert each char to int
.ToArray(); // Convert IEnumerable from select to Array
Alternatively, by using the BitArray class-
BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();
Source: https://stackoverflow.com/a/6758288/1560697
I am using BitConverter.ToString(bytes) for converting by string to hexadecimal string which I further convert it into integer or float.
But the input stream consist of 0 to show that byte value is 0. So suppose I have an integer which is represented by 2 bytes of input starting at position x and the first consist of EE while 2nd byte is 00. Now when I use BitConverter.ToString(bytes, x, 2).Replace ("-","") I get output as EE00 whose integer value is 60928 but in this case the output should be 238 that is converting only first byte EE to integer.
But in some other case the 2 bytes might be EE01 whose integer value will 60929 which is correct in this case.
Any suggestion how can I solve my problem?
Since some people are saying that question is confusing I will restate my problem I have long hexadecimal string as input. In hexadecimal string the
1) First 12 bytes represent string.
2) next 11 bytes also represent some other string.
3) Next 1 byte represent integer.
4) Next 3 bytes represent integer.
5) Next 4 bytes represent integer.
6) Next 4 bytes represent float.
7) Next 7 bytes represent string.
8) Next 5 bytes represent integer.
So for 4th case if bytes are ee 00 00 then I should neglect 0's and convert ee to integer. But if it ee 00 ee then I should convert ee00ee to integer. Also every time I will be following same pattern as mentioned above.
This method converts a hex string to a byte array.
public static byte[] ConvertHexString(string hex)
{
Contract.Requried(!string.IsNullOrEmpty(hex));
// get length
var len = hex.Length;
if (len % 2 == 1)
{
throw new ArgumentException("hexValue: " + hex);
}
var lenHalf = len / 2;
// create a byte array
var bs = new byte[lenHalf];
try
{
// convert the hex string to bytes
for (var i = 0; i != lenHalf; i++)
{
bs[i] = (byte)int.Parse(hex.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
}
catch (Exception ex)
{
throw new ParseException(ex.Message, ex);
}
// return the byte array
return bs;
}
From the other side:
public static string ConvertByteToHexString(byte num)
{
var text = BitConverter.ToString(new[] { num });
if (text.Length == 1)
{
text = "0" + text;
}
return text;
}
My problem has been solved. I was making a mistake of Endianness. I was receiving the data as EE 00 and I should have taken it as 00 EE before converting to integer. Thanks to all who gave me solution for my problem and sorry for missing out this important fact from question.
Is there something similar to sprintf() in C#?
I would for instance like to convert an integer to a 2-byte byte-array.
Something like:
int number = 17;
byte[] s = sprintf("%2c", number);
string s = string.Format("{0:00}", number)
The first 0 means "the first argument" (i.e. number); the 00 after the colon is the format specifier (2 numeric digits).
However, note that .NET strings are UTF-16, so a 2-character string is 4 bytes, not 2
(edit: question changed from string to byte[])
To get the bytes, use Encoding:
byte[] raw = Encoding.UTF8.GetBytes(s);
(obviously different encodings may give different results; UTF8 will give 2 bytes for this data)
Actually, a shorter version of the first bit is:
string s = number.ToString("00");
But the string.Format version is more flexible.
EDIT: I'm assuming that you want to convert the value of an integer to a byte array and not the value converted to a string first and then to a byte array (check marc's answer for the latter.)
To convert an int to a byte array you can use:
byte[] array = BitConverter.GetBytes(17);
but that will give you an array of 4 bytes and not 2 (since an int is 32 bits.)
To get an array of 2 bytes you should use:
byte[] array = BitConverter.GetBytes((short)17);
If you just want to convert the value 17 to two characters then use:
string result = string.Format("{0:00}", 17);
But as marc pointed out the result will consume 4 bytes since each character in .NET is 2 bytes (UTF-16) (including the two bytes that hold the string length it will be 6 bytes).
It turned out, that what I really wanted was this:
short number = 17;
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
writer.Write(number);
writer.Flush();
The key here is the Write-function of the BinaryWriter class. It has 18 overloads, converting different formats to a byte array which it writes to the stream. In my case I have to make sure the number I want to write is kept in a short datatype, this will make the Write function write 2 bytes.