C / C ++中的任意大小整数 [英] Arbitrary size integers in C/C++
本文介绍了C / C ++中的任意大小整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 有没有办法用c / c ++创建任意大小的整数?
例如:
int main(void) {
Int i = Int(3); //3-bit integer
i = 1; //Represented as: 001
}
奖金
- 有没有办法对浮动值做同样的事情?
推荐答案
你不能创建大小小于 char
的整数(也就是说,每个对象都有以字节为单位的大小,是 sizeof(char)
的倍数,即1)。但这不是问题,因为你可以在更大的数字内打包数字。
You can't create integers of size less than char
(that is, each object has a size in bytes that's a multiple of sizeof(char)
, which is 1). But that's not a problem since you can pack numbers inside a larger number.
const unsigned size_in_bits = 3;
unsigned a = 1; // 001
unsigned b = 5; // 101
unsigned packed = (b << size_in_bits*1) | (a << size_in_bits*0); // 101001
unsigned unpacked_a = (packed >> size_in_bits*0) & ((1 << size_in_bits)-1);
unsigned unpacked_b = (packed >> size_in_bits*1) & ((1 << size_in_bits)-1);
或使用位域(语法更好,但二进制布局是实现定义的)
or use bitfields (the syntax is nicer, but the binary layout is implementation-defined)
struct Date
{
unsigned day : 5;
unsigned month : 4;
unsigned year : 21;
};
Date d;
d.day = 5; d.month = 11; d.year = 2014;
这篇关于C / C ++中的任意大小整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文