-3

How can I convert a short to an array of booleans (bool[]) in C#? I'm looking for an algorithm, multiple options would be appreciated with their pros and cons.

So for example if I have a short that = 132 that is 10000100 in binary

So I want an array of {false, false, true, false, false, false, false, true }

bool[] ToArrayOfBool(short source)
{
    bool[] result = new bool[16];

    ///Do Some stuff here


    return result;
}
TheColonel26
  • 2,618
  • 7
  • 25
  • 50

6 Answers6

5

You can use the BitArray class:

byte input = 132;
var bits = new BitArray(new byte[] { input });
foreach (var b in bits)
{
    Console.WriteLine(b);
}

This produces an IEnumerable<bool> but you can also convert it to an array:

byte input = 132;
var bits = new BitArray(new byte[] { input }).Cast<bool>().ToArray();
foreach (var b in bits)
{
    Console.WriteLine(b);
}

Output:

False
False
True
False
False
False
False
True

You can also just leave it as a short, and get the bits you need using an extension method like this one:

public static bool GetBit(this short This, int bitNumber)
{
    return (This & (1 << bitNumber)) != 0;
}

for (int i=0; i<8; i++)
{
    Console.WriteLine(input.GetBit(i));
}

Example on DotNetFiddle

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • In a standard bit interpretation of a decimal, isn't the most significant bit supposed to come first? For example, I would expect the output above to be 132 = 10000100. – spencer741 Jan 30 '23 at 20:29
  • For example, referencing your last example and dotnet fiddle... I would expect something like `(decimal & ( 1 << (8-i))) != 0` which preserves the standard bit interpretation (most-significant-bit first) of the decimal. Your example seems to convert to a least-significant-bit first interpretation. – spencer741 Jan 30 '23 at 21:00
  • The issue is not LSB or MSB. The issue is your definition of the word "first." Bits in a byte are typically numbered from 0 to 7 *from right to left*. The numbers correspond to the power of 2, e.g. bit 0 is 2^0, bit 1 is 2^1, and bit 7 is 2^7. The 7th bit is the most significant (and is typically "first," i.e. leftmost, within a byte, when written out). – John Wu Jan 30 '23 at 21:21
  • "Bits in a byte are typically numbered from 0 to 7 from right to left." ... Yes, so assuming a 'typical' interpretation as you stated, shouldn't your code output the bool array (right to left) 10000100 instead of 00100001 to represent the decimal 132? I think we are on the same page on what "first" [means](https://en.wikipedia.org/wiki/Bit_numbering#Most-_vs_least-significant_bit_first). – spencer741 Jan 30 '23 at 22:04
2
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.WriteLine($"132 = {string.Join(",", ConvertToArray(132))}");
            Console.ReadKey();
        }

        static bool[] ConvertToArray(short @short)
        {
            var result = new bool[16];
            for (int i = 0; i < 16; i++)
            {
                result[i] = (@short & (short)1) == (short)1 ? true : false;
                @short = (short)(@short >> 1);
            }
            return result;
        }

    }
}
Shaoming
  • 39
  • 3
1
for (int i = 0; i < 16; i++) {
    // Single bit bitmask at index i: 0b0001, 0b0010, 0b0100 etc..
    int bitmask = 1 << i;
    // Check to see if the bit at that mask is set.
    result[i] = (source & bitmask) != 0;
}
ILMTitan
  • 10,751
  • 3
  • 30
  • 46
0

clue

var bits = new bool[16];
if(i &x0001) bits[0] = true;
if(i &x0002) bits[1] = true;
pm100
  • 48,078
  • 23
  • 82
  • 145
0

Looks like you have three steps:

  1. Convert to binary first using Convert.ToString(myshort, 2) where myshort is your value.

  2. Loop through each character of the string and test if it equals 1 and add each to a bool array.

  3. Reverse the array (or you can reverse the string after step 1)

Because I'm bored, here's an example :)

    short myshort = 132;
    Console.WriteLine("Short: " + myshort);

    var binarystring = Convert.ToString(myshort, 2);
    Console.WriteLine("Binary: " + binarystring);

    var boolarray = new bool[binarystring.Length];

    for (var i = 0; i < binarystring.Length; i++) {
        boolarray[i] = binarystring[i] == '1';          
    }

    Array.Reverse(boolarray);

    //output result     
    foreach (var b in boolarray) {
        Console.Write(b.ToString() + ", ");
    }

The output is:

Short: 132
Binary: 10000100
False, False, True, False, False, False, False, True,
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
0

So thanks to @pm100 this is what I came up with

public bool[] ToArrayOfBool(short source)
{
    bool[] result = new bool[16];

    for (int i = 0; i < 16; i++)
    {
        result[i] = (source & (i * i)) == i * i; 
    }

    return result;
}
TheColonel26
  • 2,618
  • 7
  • 25
  • 50