2012-06-23 20 views
3

我使用位打開和關閉,這樣轉位:設置有點與另一個無符號的字符的另一位unsigned char型的無條件

unsigned char myChar = ...some value 
myChar |= 0x01 << N // turn on the N-th bit 

myChar &= ~(0x01 << N) //turn off the N-th bit 

現在,假設N的值是知道的,但設置/取消設置操作取決於另一個無符號字符的位的值。 因爲現在,我做的是這樣的:

if ((otherChar & (0x01 << M)) != 0) 
{ 
    //M-th bit of otherChar is 1 
    myChar |= 0x01 << N; 
}else 
{ 
    myChar &= ~(0x01 << N); 
} 

這應該是從unsigned char類型到另一種「移動位」的操作。

我的問題: 有沒有辦法做到這一點,而不使用條件? (也沒有std :: bitset)

+0

當你說'N次bit',是再從零開始計數? – Nawaz

+0

yes..zero based.Is this relevant? – Heisenbug

回答

3

簡短回答是「是」。

較長的答案是,你直接使用位來自源:

unsigned char bit = 1 << N; 

myChar &= ~bit;    // Zero the bit without changing anything else 
myChar |= otherChar & bit; // copy the bit from the source to the destination. 

這是假定你想從源到目的地的N位複製N位。如果源和目標位可能處於不同的偏移量,事情會變得更加困難。你不僅要從源頭中提取正確的位,而且還必須將它移到正確的位置,然後將它移到目標位置。基本的想法就像上面那樣,但是轉換的代碼有點乏味。問題是,你願意做這樣的事情:

unsigned char temp = source & 1 << M; 
temp <<= N - M; 
dest |= temp; 

這將正常工作,如果N> M,但如果M> N,你最終像temp <<= -3;。你會將-3左移最終作爲右移3 - 但這不是發生了什麼,所以你需要一些條件代碼來獲取絕對值,並找出是否要做右移或左移以將來自源的位移入目的地中的正確位置。

+0

哦,謝謝..它沒有出現在我的腦海裏。 – Heisenbug

+0

這不會從'otherChar'讀取M位。 –

+0

@MarkTolonen:你說得對,它使用的變量與他在問題中所做的不同。我已經重寫了它,以同樣的方式使用相同的(我認爲,無論如何)變量,就像他在問題中所做的一樣。 –

3

一個解決方案是首先總是取消設置該位,然後按位或在otherChar的適當移位和屏蔽版本中。

2

它從位讀取c1的位,並將其寫入的位c2。

#include <stdio.h> 

typedef unsigned char uchar; 

uchar move_bit(uchar c1, int from, uchar c2, int to) 
{ 
    int bit; 
    bit = (c1 >> from) & 1;   /* Get the source bit as 0/1 value */ 
    c2 &= ~(1 << to);     /* clear destination bit */ 
    return (uchar)(c2 | (bit << to)); /* set destination bit */ 
} 

int main() 
{ 
    printf("%02X\n",move_bit(0x84,3,0x42,5)); 
    printf("%02X\n",move_bit(0x81,0,0x03,7)); 
    printf("%02X\n",move_bit(0xEF,4,0xFF,6)); 
    return 0; 
} 

結果:

42 
83 
BF 
相關問題