Arbitrary size integers in C/C++

后端 未结 5 682
眼角桃花
眼角桃花 2020-12-31 21:52

Question

  • Is there a way to create a arbitrary size integer using c/c++?

For example:

int main(void) {
  Int i = Int(3); //3-bit i         


        
5条回答
  •  醉梦人生
    2020-12-31 22:14

    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;
    

提交回复
热议问题