Converting from string bits to byte or hex - c#

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

Related

How do i create byte array that contains 64 bits array and how do i convert those bits into hex value?

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

C# Converting a string value to a byte

I need a bit of help, How would I go about converting the below to a byte.
string s = "0x01";
byte b = Convert.toByte(s); //(Tried this) ??
byte c = byte.Parse(s); //(Tried this as well)
How would I convert s to a byte ?
I guess the parse function won't allow the prefix 0X in the string so you might use sub-string to remove it.
byte myByte = Byte.Parse(s.SubString(2), NumberStyles.HexNumber);
Or use -
byte myByte = Convert.ToByte(s,16);
Firstly, remove "0x" from the string value and then use parse() method with NumberStyles.HexNumber
string s = "AA";
byte byteValue = 0;
try
{
byteValue = byte.Parse(s, NumberStyles.HexNumber | NumberStyles.AllowHexSpecifier);
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("String value: 0x{0}, byte value: {1}", s, byteValue);

How to convert a string to byte array

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

Convert int to hex format 0xyy c#

I need to write a function which receives one parametrer of type int (decimal), and returns string containing the int value in hex, but in format 0xyy.
More than that I want the answer to be in a fixed format of 4 Bytes
For example:
int b = 358;
string ans = function(b);
In this case ans = "0x00 0x00 0x01 0x66"
int a = 3567846;
string ans = function(a);
In this case ans = "0x00 0x36 0x70 0xE6"
This should match your examples:
static string Int32ToBigEndianHexByteString(Int32 i)
{
byte[] bytes = BitConverter.GetBytes(i);
string format = BitConverter.IsLittleEndian
? "0x{3:X2} 0x{2:X2} 0x{1:X2} 0x{0:X2}"
: "0x{0:X2} 0x{1:X2} 0x{2:X2} 0x{3:X2}";
return String.Format(format, bytes[0], bytes[1], bytes[2], bytes[3]);
}
I think the format you want is on similar lines
int ahex = 3567846;
byte[] inthex = BitConverter.GetBytes(ahex);
Console.WriteLine("0x"+ BitConverter.ToString(inthex).Replace("-"," 0x"));

How convert int's to byte array with two fixed values

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 };

Categories

Resources