2017-04-06 297 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; 
});