0

I have an array of integer 1s and 0s (possibly need to get converted to byte type?). I have used an online ASCII to binary generator to get the equivalent binary of this 6 digit letter sequence:

abcdef should equal 011000010110001001100011011001000110010101100110 in binary. So in c#, my array is [0,1,1,0,0,0,0...], built by:

int[] innerArr = new int[48]; 
for (int i = 0; i < 48); i++) {
    int innerIsWhite = color.val[0] > 200 ? 0 : 1;
    innerArr[i] = innerIsWhite;
}

I want to take this array, and convert it into abcdef (and be able to do the opposite).

How do I do this? Is there a better way to be storing these ones and zeros.

mheavers
  • 29,530
  • 58
  • 194
  • 315
  • 3
    In terms of better ways to store sequences of bits, rather than a string, you could use a [BitArray](https://learn.microsoft.com/en-us/dotnet/api/system.collections.bitarray?view=netframework-4.7.2). – Joe Sewell Feb 20 '19 at 19:12
  • https://stackoverflow.com/questions/6006425/binary-to-corresponding-ascii-string-conversion First Answer has the information you need – Darnold Feb 20 '19 at 19:13
  • @mheavers I can verify you can create a `BitArray` with 48 elements - `new BitArray(48)`. – Joe Sewell Feb 20 '19 at 19:37

2 Answers2

1

Try using Linq and Convert:

  source = "abcdef";

  // 011000010110001001100011011001000110010101100110 
  string encoded = string.Concat(source
    .Select(c => Convert.ToString(c, 2).PadLeft(8, '0')));

  // If we want an array
  byte[] encodedArray = encoded
    .Select(c => (byte) (c - '0'))
    .ToArray();

  // string from array
  string encodedFromArray = string.Concat(encodedArray);

  // abcdef
  string decoded = string.Concat(Enumerable
    .Range(0, encoded.Length / 8)
    .Select(i => (char) Convert.ToByte(encoded.Substring(i * 8, 8), 2)));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

If your input is a bit string, then you can use a method like below to convert that into character string

public static string GetStringFromAsciiBitString(string bitString) {
    var asciiiByteData = new byte[bitString.Length / 8];
    for (int i = 0, j = 0; i < asciiiByteData.Length; ++i, j+= 8)
        asciiiByteData[i] = Convert.ToByte(bitString.Substring(j, 8), 2);
    return Encoding.ASCII.GetString(asciiiByteData);
}

The above code simply uses the Convert.ToByte method asking it to do a base-2 string to byte conversion. Then using Encoding.ASCII.GetString, you get the string representation from the byte array

In my code, I presume your bit string is clean (multiple of 8 and with only 0s and 1s), in production grade code you will have to sanitize your input.

Vikhram
  • 4,294
  • 1
  • 20
  • 32