String to byte hex convert - c#

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"));

Related

Cast string to hex byte array [duplicate]

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")));

c# bitconverter.ToString convert to hexadecimal string

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.

Converting Hexidecimal Strings to Numeric Types and back

I need a function to convert hex values in the format 0xFFFF (2 Bytes) to decimal (unsigned and signed).
For example:
0xFFFE is 65534 (unsigned)
0xFFFE is -2 (signed)
I need also the same thing for 4 Bytes and 1 Byte.
All these options (3 * 2 options) I need to convert back - from decimal to hex (total 12 options).
My function should look like this:
string Myconverter(int ByteSize, bool IsFromHextoDecimal, bool IsSigned)
{
...
}
If there's build in functionality that performs these conversions, I'd like to a reference/link.
Use methods in the Convert class to parse the string to a number. To parse an unsigned 2 byte value you use the ToUInt16 method, and specify the base 16:
ushort value = Convert.ToUInt16("0xFFFF", 16);
Use these methods for other format:
ToInt16 = signed 2 byte
ToUInt32 = unsigned 4 byte
ToInt32 = signed 4 byte
ToByte = unsigned 1 byte
ToSByte = signed 1 byte
To format a number to a hexadecimal string you can use the X format (or x to get lower case letters) and specify the number of digits:
string formatted = value.ToString("X4");
That will however not have the 0x prefix, so if you want that you have to add it:
string formatted = "0x" + value.ToString("X4");

Convert object to byte array in c#

I want to convert object value to byte array in c#.
EX:
step 1. Input : 2200
step 2. After converting Byte : 0898
step 3. take first byte(08)
Output: 08
thanks
You may take a look at the GetBytes method:
int i = 2200;
byte[] bytes = BitConverter.GetBytes(i);
Console.WriteLine(bytes[0].ToString("x"));
Console.WriteLine(bytes[1].ToString("x"));
Also make sure you have taken endianness into consideration in your definition of first byte.
byte[] bytes = BitConverter.GetBytes(2200);
Console.WriteLine(bytes[0]);
Using BitConverter.GetBytes will convert your integer to a byte[] array using the system's native endianness.
short s = 2200;
byte[] b = BitConverter.GetBytes(s);
Console.WriteLine(b[0].ToString("X")); // 98 (on my current system)
Console.WriteLine(b[1].ToString("X")); // 08 (on my current system)
If you need explicit control over the endianness of the conversion then you'll need to do it manually:
short s = 2200;
byte[] b = new byte[] { (byte)(s >> 8), (byte)s };
Console.WriteLine(b[0].ToString("X")); // 08 (always)
Console.WriteLine(b[1].ToString("X")); // 98 (always)
int number = 2200;
byte[] br = BitConverter.GetBytes(number);

Equivalent of sprintf in C#?

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.

Categories