簡體   English   中英

C++ 位操作

[英]C++ bit manipulation

我正在嘗試從 UTF-8 格式中提取字符值。 假設我有兩個字符,我從第一個字符 => 10111 中提取 5 位,從另一個字符 => 010000 中提取 6 位

所以

ch1 = 10111;
ch2 = 010000;

我如何將它們組合成 10111010000 和 output 其十六進制為 0x5d0? 我是否需要轉移或有更簡單的方法可以做到這一點,因為檢查文檔write似乎能夠順序讀取字符,是否有類似的 function 像這樣? 此外,我似乎需要一個字符緩沖區,因為 10111010000 是 11 位長。 有誰知道 go 關於這個?

您需要使用移位,加上| |=運算符。

unsigned int ch3 = (ch1 << 6) | ch2;
// ch3 = 0000010111010000

我在這里假設unsigned int是 16 位。 你的旅費可能會改變。

您肯定需要使用 shift 和 OR。

首先,聲明一個大小合適的無符號 integer 類型。 我喜歡 stdint.h 中定義的 C99 類型,但您的 C++ 編譯器可能沒有它們。 如果你沒有uint16_t那么你可以使用unsigned short 那是 16 位寬,可以容納 11 位。

然后你會弄清楚哪些位 go 進入高位。 看起來應該是:

unsigned short ch1 = 0x17;
unsigned short ch2 = 0x10;
unsigned short result = (ch1 << 6) | ch2;

1:將它們組合在一起:

char bytes[2] = { 0x17, 0x10 }; // for example

unsigned short result = 0;      // 00000000  00000000
result = bytes[0] << 6;         // 101 11000000
result |= bytes[1];             // 101 11010000

2:用於將其打印為十六進制

std::cout << std::showbase << std::hex << <what you want to print>;

在這種情況下:

std::cout << std::showbase << std::hex << result
// output: 0x5d0 if it is little-endian, it depends on your operating system

首先,來自 K&R:“關於位域的幾乎所有內容都取決於實現”。

以下適用於 MS Visual Studio 2008:

#include <stdio.h>
#include <string.h>

struct bitbag {
    unsigned int ch2 : 6;
    unsigned int ch1 : 6;
};

int main ()
{
    struct bitbag bits;

    memset(&bits, 0, sizeof(bits));

    bits.ch1 = 0x17;    // 010111
    bits.ch2 = 0x10;    // 010000

    printf ("0x%06x 0x%06x\n", bits.ch1, bits.ch2);
    printf ("0x%0x\n", bits);

    return 0;
}

產生 output:

0x000017 0x000010
0x5d0

但是我不能保證它會在所有編譯器中以相同的方式工作。 請注意將任何填充初始化為零的memset

暫無
暫無

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

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