所以我寫了下面的代碼,它接受一個 unsigned int ,將它的第 6 位向左移動,然后用另一個 int 值替換空的最后 6 位。但是,當我使用值 15 運行代碼 say 時,第一步有效,我得到的值為 960(因此向左移動 6 有效)。但是 or 步驟似乎不起作用,當我實際上需要獲得 1111111111111111 或即 65535 時,我得到 -1(注意在這種情況下的運算元值為 -1)?任何幫助將不勝感激。我知道這可能與我的型別有關,但是 s->data 被定義為無符號 int 而運算元被定義為 int 所以我不知道為什么 s->data 的輸出給出了負值。
typedef struct state { int x, y, tx, ty; unsigned char tool; unsigned int start, data; bool end;} state;
void dataCommand(int operand, state *s) {
// shifts bits of current data fields six positions to left
printf("BEFORE SHIFTING %d\n", s->data);
s->data = s->data << 6;
printf("AFTER SHIFTING %d\n", s->data);
printf("OPERAND IS %d\n", operand);
// last 6 bits replaced with operand bits of the command
s->data = (s->data | operand);
printf("AFTER OR %d\n", s->data);
}
uj5u.com熱心網友回復:
當operand是 -1 時,它實際上是0xffffffff(二進制中的 32 個)。因此,當您進行 ORing 時,您會得到 32 個仍然為 -1 的結果。
也許您想要做的是屏蔽運算元??的 6 位:
s->data = (s->data << 6) | (operand & 0b111111);
uj5u.com熱心網友回復:
您必須屏蔽operand以選擇將哪些位組合到結果中。
-1unsigned int在s->data | operand運算式中被轉換為UINT_MAX設定了所有位的值,因此 oringoperand設定結果中的所有位,給它一個值UINT_MAX,但是由于您%d用來輸出該值,您得到-1.
這樣修改代碼:
typedef struct state {
int x, y, tx, ty;
unsigned char tool;
unsigned int start, data;
bool end;
} state;
void dataCommand(int operand, state *s) {
// shifts bits of current data fields six positions to left
printf("BEFORE SHIFTING %u\n", s->data);
s->data = s->data << 6;
printf("AFTER SHIFTING %u\n", s->data);
printf("OPERAND IS %d (%#x)\n", operand, operand);
// last 6 bits replaced with operand bits of the command
s->data = s->data | (operand & 0x3F);
printf("AFTER OR %u\n", s->data);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/368924.html
