简体   繁体   中英

How to convert an integer to binary stored in array

I know how to convert an integer from decimal to fixed length binary string:

int number = 3;
int toBase = 2;
int length = 8;
Convert.ToString(number, toBase).PadLeft(length, '0')

Output:

00000011

How to assign the individual elements of that binary string to either int (or bool ) array, such that after the conversion the array will look like 1 :

int[] binary = {0, 0, 0, 0, 0, 0, 1, 1}

or

bool[] binary = {false, false, false, false, false, false, true, true};

1. Using the facilities and not trivial for loop with char to int (or bool ) type conversions.

If you store the string you have created, for example

string theBinaryString = Convert.ToString(number, toBase).PadLeft(length, '0');
int[] binary = new int[8];
for(int i = 0; i < 8; i++)
{
    binary[i] = int.parse(theBinaryString[i].ToString());
}

Once the loop has finished you will have the array you are looking for, the ToString() is required as selecting from a string as if it was an array returns a char, which cannot be parsed into an int.

You can add some Linq to represent the string as an array:

string source = Convert.ToString(number, toBase).PadLeft(length, '0');

...

int[] binary = source.Select(c => c - '0').ToArray();

...

bool[] binary = source.Select(c => c == '1').ToArray();

Or you can compute arrays directly:

int[] binary = Enumerable
  .Range(1, length)
  .Select(i => number / (1 << (length - i)) % 2)
  .ToArray();

bool[] binary = Enumerable
  .Range(1, length)
  .Select(i => number / (1 << (length - i)) % 2 == 1)
  .ToArray(); 

maybe like this;

"1000110101110".ToCharArray().Select(c => c - '0').ToArray()

will give you:

int[13] { 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0 }

You can do it without converting the number to binary string:

var num = 123;
var bits = Enumerable.Range(0, 8).Select(i => (num >> (7-i)) & 1).ToArray();

The idea is to shift the number right sequentially by a decreasing number of positions, and mask off all bits except least significant one.

Demo.

int[] intArray = stringNumber.ToCharArray().Select(n => Convert.ToInt32(n)).ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM