Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
hello
i am trying my own implementation of a big int class using string manipulation


but since each string digit takes up 8 bits of memory i want to use 4 bits for the digit, instead of the whole byte. Thus, the number 123,456 might be represented by the bytes 12 34 56 instead of the string 123456. (Three bytes as opposed to six.)

help please ;
Posted
Comments
Sergey Alexandrovich Kryukov 24-Dec-15 13:29pm    
It's easy: back two digits in one byte. But I'm not sure your binary-decimal approach is the best for big int.
Why not using the system with the base 256, for example, in exact same way? Then you would need conversion to decimal and from decimal only when you first enter data or output as string. You never really need decimal for calculations.
—SA

What you want is BCD.

Binary-coded decimal - Wikipedia, the free encyclopedia[^]

When viewed as hexadecimal, the decimal digit pair appear like decimal.

C++
const char *text = "123456";

std::vector<unsigned char> number;

while (*text)
{
    unsigned char pair = 0;
    unsigned char digit = *text++;
    digit -= '0';
    pair = digit;
    if (*text)
    {
        digit = *text++;
        digit -= '0';
        pair <<= 4;
        pair |= digit;
    }
    number.push_back(pair);
}

for (int i = 0; i < number.size())
{
    printf("%02X", number[i]);
}
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 24-Dec-15 14:01pm    
Nice explanation, a 5.
—SA
Member 12223678 24-Dec-15 14:53pm    
how can i implement that inside my big integer class
Philippe Mori 24-Dec-15 20:44pm    
Write code, more code and a lot of code...
[no name] 24-Dec-15 15:18pm    
I have no information on your big integer class.
Have a look at my article An introduction to bitwise operators[^]. You can accomplish what you want using the AND, OR, and SHIFT operators.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900