Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arbitrary size integers in C/C++

Tags:

c++

c

integer

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 integer
  i = 1; //Represented as: 001
}

Bonus

  • Is there a way to do the same with floating values?
like image 947
Simón Oroño Avatar asked Feb 23 '15 23:02

Simón Oroño


2 Answers

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;
like image 136
milleniumbug Avatar answered Sep 18 '22 13:09

milleniumbug


You could try the GNU Multiple Precision Arithmetic Library library, which supports both integers, fractions, and real numbers.

like image 42
Aasmund Eldhuset Avatar answered Sep 21 '22 13:09

Aasmund Eldhuset