I'm sending five bytes to an Arduino:
byte[] { 0xF1, byte1, byte2, byte3, 0x33 }
The values of byte1, byte2 and byte3 are dynamic. The first and last bytes are always the same.
Byte values are from 0 to 255.
How can I simply convert ints to bytes and put them into my byte array?
To get array of bytes from int use:
byte[] intAsArrayOfBytes = BitConverter.GetBytes(yourInt);
then you can copy values to your array
byte[] { 0xF1, intAsArrayOfBytes[0], intAsArrayOfBytes[1], intAsArrayOfBytes[3], 0x33 }
or if you need just convert int type into byte type and you know that variable between 0..255 use:
byte byte1 = (byte) int1;
byte byte2 = (byte) int2;
byte byte3 = (byte) int3;
If you are sure that your values won't exceed the byte range [0, 255], you can simply cast them:
byte[] b = { 0xF1, (byte)byte1, (byte)byte2, (byte)byte3, 0x33 }
In alternative you can use Convert.ToByte, which throws an OverflowException if values are less than 0 or greater than 255.
Assuming the ints are between 0 and 255, use Convert.ToByte(). For example:
int byte1;
int byte2;
int byte3;
byte[] bytes = new byte[]{ 0xF1, Convert.ToByte(byte1),
Convert.ToByte(byte2), Convert.ToByte(byte3), 0x33 };
Related
Example, I want to convert 3 bytes to ASCII conversion
int a = random.Next(0, 100);
int b = random.Next(0, 1000);
int c = random.Next(0, 30);
byte[] byte1 = BitConverter.GetBytes(a);
byte[] byte2 = BitConverter.GetBytes(b);
byte[] byte3 = BitConverter.GetBytes(c);
byte[] bytes = byte1.Concat(byte2).Concat(byte3).ToArray();
string asciiString = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
label1.Text = asciiString;
It only shows byte1 instead of all bytes.
If you look in the debugger at your asciiString variable you will see that all the 3 letters are there, but in between you always have a 0x00 char.
(screenshot from LINQPad Dump)
This is unfortunately interpreted as end of string. So this is why you see only the first byte/letter.
The documentation of GetBytes(char) says that it returns:
An array of bytes with length 2.
if you now get the bytes from a single char:
byte[] byte1 = BitConverter.GetBytes('a');
You get the following result:
The solution would be to pick only the bytes that are not 0x00:
bytes = bytes.Where(x => x != 0x00).ToArray();
string asciiString = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
label1.Text = asciiString;
This example is based on the char variant of GetBytes. But it holds for all other overloads of this method. They all return an array which can hold the maximum value of the corresponding data type. So this will happen always if the value is so small that the last byte in the array is not used and ends up to be 0!
I want to create byte array that contains 64 bits, How can i get particular bits values say 17th bit, and also how can i get hex value of that index of byte? I did like this, Is this correct?
byte[] _byte = new byte[8];
var bit17=((((_byte[2]>>1)& 0x01);
string hex=BitConverter.ToString(_byte,2,4).Replace("-", string.Empty)
You could use a BitArray:
var bits = new BitArray(64);
bool bit17 = bits[17];
I'm not sure what you mean by the "hex value of that bit" - it will be 0 or 1, because it's a bit.
If you have the index of a bit in a byte (between 0 and 7 inclusive) then you can convert that to a hex string as follows:
int bitNumber = 7; // For example.
byte value = (byte)(1 << bitNumber);
string hex = value.ToString("x");
Console.WriteLine(hex);
You can just use ToString() method.
byte[] arr= new byte[8];
int index = 0;
string hexValue = arr[index].ToString("X");
oxfc is negative but I have it as a byte and its value is 252, is there any way to convert it to signed byte or int?
I found this method:
(BitConverter.ToInt16(new byte[2] { 0, 0xfc }, 0) / 256).ToString()
But is there any better way?
You can simply cast it:
byte b = 0xfc;
sbyte s = unchecked((sbyte)b);
I have a string and want to convert it to a byte array of hex value using C#.
for eg, "Hello World!" to byte[] val=new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21};,
I see the following code in Converting string value to hex decimal
string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
// Get the integral value of the character.
int value = Convert.ToInt32(letter);
// Convert the decimal value to a hexadecimal value in string form.
string hexOutput = String.Format("0x{0:X}", value);
Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
I want this value into byte array but can't write like this
byte[] yy = new byte[values.Length];
yy[i] = Convert.ToByte(Convert.ToInt32(hexOutput));
I try this code referenced from How to convert a String to a Hex Byte Array? where I passed the hex value 48656C6C6F20576F726C6421 but I got the decimal value not hex.
public byte[] ToByteArray(String HexString)
{
int NumberChars = HexString.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
}
return bytes;
}
and I also try code from How can I convert a hex string to a byte array?
But once I used Convert.ToByte or byte.Parse , the value change to decimal value.
How should I do?
Thanks in advance
I want to send 0x80 (i.e, 128) to serial port but when I copy and paste the character equivalent to 128 to the variable 'input' and convert to byte, I got 63 (0x3F). So I think I need to send hex array. I think I got the wrong idea. Pls see screen shot.
For now, I solve this to combine byte arrays.
string input = "Hello World!";
byte[] header = new byte[] { 2, 48, 128 };
byte[] body = Encoding.ASCII.GetBytes(input);
Hexadecimal has nothing to do with this, your desired result is nothing more nor less than an array of bytes containing the ASCII codes.
Try Encoding.ASCII.GetBytes(s)
There's something strange with your requirement:
I have a string and want to convert it to a byte array of hex value
using C#.
An byte is just an 8-bit value. You can present it as decimal (e.g. 16) or hexidecimal (e.g. 0x10).
So, what do you realy want?
In case you are really wanting to get a string which contains the hex representation of an array of bytes, here's how you can do that:
public static string BytesAsString(byte[] bytes)
{
string hex = BitConverter.ToString(bytes); // This puts "-" between each value.
return hex.Replace("-",""); // So we remove "-" here.
}
It seems like you’re mixing converting to array and displaying array data.
When you have array of bytes it’s just array of bytes and you can represent it in any possible way binary, decimal, hexadecimal, octal, whatever… but that is only valid if you want to visually represent these.
Here is a code that manually converts string to byte array and then to array of strings in hex format.
string s1 = "Stack Overflow :)";
byte[] bytes = new byte[s1.Length];
for (int i = 0; i < s1.Length; i++)
{
bytes[i] = Convert.ToByte(s1[i]);
}
List<string> hexStrings = new List<string>();
foreach (byte b in bytes)
{
hexStrings.Add(Convert.ToInt32(b).ToString("X"));
}
I have a string that contains the following 7 bits: 1101000. How can I convert it to a byte or int?
This should do it:
string binaryText = "1101000";
int value1 = Convert.ToInt32(binaryText, 2) // 104
byte value2 = Convert.ToByte(binaryText, 2); // 104
to convert into byte array:
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
byte [] dBytes = encoding.GetBytes(str);