Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How convert short[] to bool[]?

short[] sBuf = new short[2];
sBuf[0] = 1;
sBuf[1] = 2;

bool[] bBuf = new bool[sBuf.Length * 16];
Buffer.BlockCopy(sBuf, 0, bBuf, 0, sBuf.Length * 2);

Desired result value  
sBuf[0] = 1
bBuf[0] = true, bBuf[1] = false, bBuf[2] = false, bBuf[3] = false...
sBuf[0] = 2
bBuf[16] = false, bBuf[17] = true, bBuf[18] = false, bBuf[19] = false...

But can not be converted correctly.
I want to convert from short [] to bool [], but I don't know how.

like image 541
Hoony Avatar asked Apr 06 '17 11:04

Hoony


People also ask

What is %d in C programming?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

What does %c mean in C?

%d is used to print decimal(integer) number ,while %c is used to print character . If you try to print a character with %d format the computer will print the ASCII code of the character.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.


1 Answers

Assuming that each bool represents a bit from its corresponding short (which is presumably why you multiplied the size by 16) you can do the conversion as follows:

bBuf = sBuf
    .SelectMany(s => Enumerable.Range(0, 16).Select(i => (s & (1<<i)) != 0))
    .ToArray();

The idea is to construct 16 booleans for each short by calling Enumerable.Range, masking the number with (1 << i), and comparing the result to zero.

like image 60
Sergey Kalinichenko Avatar answered Oct 26 '22 18:10

Sergey Kalinichenko