在C中的整数位店 [英] store bits in an integer value in c

查看:118
本文介绍了在C中的整数位店的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个8位编译说的Turbo C,在此我们有大小的整数,例如2-词语即16位或2字节。我需要存储三个整数值。

Consider an 8-bit complier say Turbo C, in which we have an integer of size, say 2-words i.e. 16-bits or 2 bytes. I need to store three integer values.

1的整数| 0-3 |的2位(二进制00-11)

Integer 1 | 0-3 | 2bits (00-11 in binary)

2的整数| 0-5 | 3比特(二进制000-101)

Integer 2 | 0-5 | 3bits (000-101 in binary)

INETGER 3 | 0-7 | 3比特(二进制000-111)

Inetger 3 | 0-7 | 3bits (000-111 in binary)

在我们总共只需要8位来存储所有这三个值。这意味着整数数据类型的一个变量有足够的内存来容纳这些值。我需要
开发一个程序,它可以 - 在最大 - 仅使用两个整数数据类型的情况下,第一个用于扫描值从标准输入设备的目的说键盘和第二个存储由用户在三个整数的形式输入的数据如上面所讨论,并通过从在其中存储的数据的第二个实例retreving它打印出来变量

In total, we need only 8 bits to store all of these three values. Which means that a single variable of integer datatype has enough memory to accomodate these values. i need to develop a program which can - at the maximum - use only two instances of integer datatype, first one for the purpose of scanning values from the standard input device say keyboard and the second one to store the data entered by user in the form of three integer variables as discussed above and print them by retreving it from the second instance in which the data was stored.

推荐答案

使用位域:

union X{
  byte byteval;
  struct {
    byte piece1:3;
    byte piece2:3;
    byte piece3:2;
  } pieces;
};

,那么你必须透明访问:

then you have transparent access :

X a;
a.pieces.piece2=3;
a.byteval;

和没有转向左,右......它留给编译器;)

and don't have to shift left and right...leave it to the compiler ;)

这篇关于在C中的整数位店的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆