Reputation: 167
I have a string,
string Var="11001100"
I want to convert it into a byte array.
bArray[0]=0x00;
bArray[1]=0x00;
bArray[2]=0x01;
bArray[3]=0x01;
bArray[4]=0x00;
bArray[5]=0x00;
bArray[6]=0x01;
bArray[7]=0x01;
Can anybody guide me in this? I tried the following code, but I get the data in ASCII. I do not want that.
bArray = Encoding.Default.GetBytes(var);
Upvotes: 0
Views: 804
Reputation: 485
This is my solution for your question:
string value = "11001100";
int numberOfBits = value.Length;
var valueAsByteArray = new byte[numberOfBits];
for (int i = 0; i < numberOfBits; i++)
{
bytes[i] = ((byte)(value[i] - 0x30)) == 0 ? (byte)1 : (byte)0;
}
Edit: Forgot the inversion.
Upvotes: 0
Reputation: 23732
but I get the data in ASCII. I do not want that.
Then you need the string representation of the chars. You get it using the ToString
method. This would be the old scool way simply using a reversed for-loop:
string Var="11001100";
byte [] bArray = new byte[Var.Length];
int countForward = 0;
for (int i = Var.Length-1; i >= 0 ; i--)
{
bArray[countForward] = Convert.ToByte(Var[i].ToString());
countForward++;
}
Upvotes: 1
Reputation: 186698
I suggest using Linq:
using System.Linq;
...
string Var = "11001100";
byte[] bArray = Var
.Select(item => (byte) (item == '0' ? 1 : 0))
.ToArray();
Test:
Console.WriteLine(string.Join(Environment.NewLine, bArray
.Select((value, index) => $"bArray[{index}]=0x{value:X2};")));
Outcome:
bArray[0]=0x00;
bArray[1]=0x00;
bArray[2]=0x01;
bArray[3]=0x01;
bArray[4]=0x00;
bArray[5]=0x00;
bArray[6]=0x01;
bArray[7]=0x01;
Upvotes: 6