gpt4 book ai didi

C++ union 位域任务

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:32:14 26 4
gpt4 key购买 nike

有人能弄清楚我为什么要使用 union 以及 cin'ed 变量和位字段的相同地址(来自 Schildts C++ 书中的任务)的目的是什么?换句话说,为什么我要使用 union for :

char ch; struct byte bit;

//显示字符的二进制ASCII码。

#include <iostream>
#include <conio.h>
using namespace std;

// a bit field that will be decoded
struct byte {
unsigned a : 1;
unsigned b : 1;
unsigned c : 1;
unsigned d : 1;
unsigned e : 1;
unsigned f : 1;
unsigned g : 1;
unsigned h : 1;
};

union bits {
char ch;
struct byte bit;
} ascii ;

void disp_bits(bits b);

int main()
{
do {
cin >> ascii.ch;
cout << ": ";
disp_bits(ascii);
} while(ascii.ch!='q'); // quit if q typed

return 0;
}

// Display the bit pattern for each character.
void disp_bits(bits b)
{
if(b.bit.h) cout << "1 ";
else cout << "0 ";
if(b.bit.g) cout << "1 ";
else cout << "0 ";
if(b.bit.f) cout << "1 ";
else cout << "0 ";
if(b.bit.e) cout << "1 ";
else cout << "0 ";
if(b.bit.d) cout << "1 ";
else cout << "0 ";
if(b.bit.c) cout << "1 ";
else cout << "0 ";
if(b.bit.b) cout << "1 ";
else cout << "0 ";
if(b.bit.a) cout << "1 ";
else cout << "0 ";
cout << "\n";
}

最佳答案

作为 union ,chbit 都有一个重叠(共享)的内存位置。将一个字符存储在其中作为 ch,然后读取 bit 为该字符生成相应的位值。

关于C++ union 位域任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3065948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com