簡體   English   中英

C ++中無符號字符的位操作

[英]bit operations on unsigned char in c++

我在 Windows 操作系統中使用 C++。

我有 2 個 values.value1 和 value 2。

我想在無符號字符的前 2 位中寫入值 1,在后 6 位中寫入值 2。

同樣,我想使用位操作從 unsigned char 中提取 value1 和 value2。

請幫助我如何實現我的要求。

請嘗試使用像這樣的位明智的運算符,

char x = (value1<<6)|(value2&0x3f); 

並提取價值,

value1 = (x>>6) & 0x3;
value2 = (x & 0x3f)
union my_char {
    unsigned char value;
    struct {
        unsigned char field1 :2;
        unsigned char field2 :6;
    };
};

my_char c;
c.value = 255;
unsigned char c1 = c.field1;
unsigned char c2 = c.field2;

編輯:

Jarod42 是對的。 根據 c++ 標准,結果是未定義的行為。 盡管所有 (?) 編譯器都可以,但您的意圖是什么(但這不是解決方案)。

這就是為什么 c++20 標准現在有一個 bit_cast ( https://en.cppreference.com/w/cpp/numeric/bit_cast )。

如果您不使用 c++20,那么您自己很容易實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM