How to save String in bits to reduce memory on occlusion

I have one array of charater pointers that points to some clutter

each element points to some lines one thing in mind lines have only 1 and 0.

eg

I have a pointer to a character that stores a string like "100110", so it takes 6 bytes to store, but I want to save this in bits to reduce the amount of memory.

+4
source share
4 answers

In C style, something like this should work:

char* str = "100101"; unsigned out = 0; for (int i = 0; str[i]; i++) { out = (out << 1); if (str[i] == '1') out++; } 

(I can't check it now, so please correct me if I am wrong)

Explanation:

 str = "100101" out = 0000 0000 0000 0000 i = 0: out = 0000 0000 0000 0000 (out << 1) out = 0000 0000 0000 0001 (out++ because str[0] == '1') i = 1: out = 0000 0000 0000 0010 (out << 1) [...] i = 5: out = 0000 0000 0010 0100 (out << 1) out = 0000 0000 0010 0101 (out++ because str[5] == '1') 
+3
source

Have you tried the STL bitset container? It is optimized for this purpose. Alternatively, creating vector elements from bool will internally package bits to save space.

+3
source

Why not use 'strtol'? This is the standard lib function. Or are you writing low-level code for low memory hardware?

 char *str = "010101"; int i = strtol(str ,(char**)NULL ,2); ==> i=21 
0
source

One way: to determine that char* [] is global and use its indexes to access it:

 char stringLiterals [] = { "0101010", "10010010", "111", "010100100", ... }; 

Usage : Instead

 char *p = stringLiteral[3]; 

using

 unsigned int idx = 3; 

Justification . If you compress this string into bits for serialization purposes, than this is normal. But otherwise, I do not see any case of compaction. In my solution above, does not use extra memory . You already have an array of string literals; I just ask you to declare it globally and use its index.

Also, if the string size is> 32 bytes, you cannot save it in a single 32-bit int .

-1
source

All Articles