Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - 3 possible values in Variable?

Tags:

c++

variables

I need to store a 30 letter combination, but each letter can only be "0", "1" or "2". When I use sizeof(myString), it returns 32.

I want to use this 30 letter combination to access a row of an array, so I'm wondering if it is possible to use a 3 value bool of some sort to store 1 of 3 values in.

like image 349
noryb009 Avatar asked Dec 10 '22 15:12

noryb009


2 Answers

3^30 = 205891132094649 (~2E14), which is less than the maximum value of a 64-bit integer (~2E19), so you could map the strings to 64-bit ints in a 1:1 fashion.

An obvious way to do this would be to treat your string as a base-3 number, which would be quite slow to convert. Much faster would be to treat it as base 4, then conversion can be done entirely with bit shifts (no modulus division / multiplication), this is possible since 4^30 is still less than 2^64.

like image 130
James Avatar answered Feb 01 '23 14:02

James


The smallest unit of size C and C++ let you deal with (without bitfields in structures that would make your code very impractical) is the char. Even bool resolves to the size of a char even though it uses only a single bit. Therefore, you won't make any memory gain from using another type. The only possible improvement would be to use a type completely different from an array.

like image 43
zneak Avatar answered Feb 01 '23 15:02

zneak