0

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);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
k11
  • 167
  • 1
  • 3
  • 16

3 Answers3

6

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;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

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++;
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • Please notice, that `bArray` should contain *inversed* values: `'1' -> 0` and `'0' -> 1` – Dmitry Bychenko Aug 18 '17 at 08:44
  • @DmitryBychenko I have the feeling that OP is reading the input from right to left (little endian fashion). Therefore I chose the reversed for loop – Mong Zhu Aug 18 '17 at 08:47
  • I see; we need a better test example to distinguish between these two possibilities... – Dmitry Bychenko Aug 18 '17 at 08:49
  • @DmitryBychenko lets see whether he answers my question from the comment – Mong Zhu Aug 18 '17 at 08:50
  • well, in case of, say, `"11010101"` the outcomes are *different*: `[0, 0, 1, 0, 1, 0, 1, 0]` (my understanding - bytes reversing) and `[0, 1, 0, 1, 0, 1, 0, 0]` (your reading - little/big endian). The test case provided `"11001100"` can't help to chose the right one (alas!) – Dmitry Bychenko Aug 18 '17 at 08:57
  • @DmitryBychenko I agree, same holds for the test case from my comment. Lets wait and see what and if OP responds to my comment – Mong Zhu Aug 18 '17 at 09:12
0

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.