2013-05-02 49 views
3

我在C#中有一個短變量,並且想要更改特定位。我怎樣才能做到這一點最簡單的方法?如何更改短內容中的位

+1

也許顯示你的短變量的代碼? – 2013-05-02 15:41:41

+0

我想編寫一個函數,它用索引x操縱位,並返回修改過的短小 – Weedjo 2013-05-02 15:43:27

+1

發佈您的代碼,我們可以進一步幫助您 – 2013-05-02 15:44:06

回答

4

在位運算符來看看:

short i = 4; 
short k = 1; 
Console.WriteLine(i | k); //should write 5 

你可以看到下Logical (boolean and bitwise)部分here運營商的列表。

另外,做了一些戳動,發現this bitwise helper class。根據您的需求值得檢查。

6

你的意思是這樣的嗎?

public static short SetBit(short input, int bit) 
{ 
    return (short) (input | (1 << bit)); 
} 

public static short ClearBit(short input, int bit) 
{ 
    return (short) (input & ~(1 << bit)); 
} 

如果你願意,你甚至可以使它們成爲擴展方法。

+0

如果你想從一個布爾輸入做到這一點,你可以添加一個方法'SetBit(短輸入,int位,布爾值){返回值? SetBit(輸入,位):ClearBit(輸入,位); }' – 2013-05-02 15:50:37