2017-04-06 56 views
8
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... 

但无法正确转换。
我想从short []转换为bool [],但我不知道如何。C#如何将short []转换为bool []?

+11

什么时候'bool'元素应该是'true'? –

+4

@cat:一个问题,以节省我一些大脑周期:) –

+1

@cat所以你想要-1,两个常用的值之一为true,为false?问问题并让OP决定是很好的。根据dasblinkenlight接受的答案,你的猜测会和我的猜想一样错误。 – hvd

回答

14

假设每个bool表示从它的对应的short(这大概是为什么你乘以16的大小)可以执行转换如下一点:

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

我们的想法是,构建16通过调用Enumerable.Range对每个short进行布尔运算,用(1 << i)掩盖该编号,并将结果与​​零进行比较。

+0

发生构建错误。 CS0019'&'操作符不能应用于'short'和'bool'类型的操作数。 – Hoony

+0

@Hoony我在复制代码后编辑了答案。一对括号丢失了。请再试一次。 – dasblinkenlight

+0

@Hoony你应该使用更新的答案括括号&&(1 << i)'实际上你可以删除内部括号:'i =>(s&1 << i)!= 0'但它不是可读的 –

4

从MSDN页面Convert.ToBoolean它说,每0值将被转换为false和每一个非0true

bool[] bBuf = new bool[sBuf.Length]; 
for(int i = 0; i < sBuf.Length; ++i) 
{ 
    bBuf[i] = Convert.ToBoolean(sBuf[i]); 
} 

编辑:
设置你的bool[]基础上设置的位short您可以使用此值:

const int BITS_PER_BYTE = 8; // amount of bits per one byte 

int elementBitsSize = sizeof(short) * BITS_PER_BYTE; // size in bits of one element in array 
bool[] bBuf = new bool[sBuf.Length * elementBitsSize]; // new array size 

// iterate through each short value 
for (int i = 0; i < sBuf.Length; ++i) 
{ 
    // iterate through bits in that value 
    for(int j = 0; j < elementBitsSize; ++j) 
    { 
     // assign new value 
     bBuf[j + i * elementBitsSize] = Convert.ToBoolean(sBuf[i] & (1 << j)); 
    } 
} 

Working example

+3

我喜欢这个解决方案,在我看来,** far **比阅读所选答案的LINQ解决方案更容易阅读。这就是说,这对于OP来说不起作用。对于“将short []转换为bool []”的明确任务,这很好(尽管我个人喜欢总是使用T.TryParse(),除非我能保证数据的完整性),但是由于OP正在处理每个'short'的个别位构建的“bool”值比他有'shorts'多16倍,这不是他正在寻找的* – sab669

1
// Convert short to bool 
bool[] bBuf = Array.ConvertAll(sBuf, n => n != 0); 

// Convert short to bit representation bool array 
bool[][] bBuf= Array.ConvertAll(arr, n => 
{ 
    bool[] bits = new bool[16]; 

    for (int index = 0; index < 16; index++) 
    { 
     bits[index] = (n & (1 << index)) > 0; 
    } 

    return bits; 
});