sam_k
sam_k

Reputation: 6023

How to store String in to bits for reduce memory occpuied

I have one charater pointer array which points to the some stirngs

every element points to some strings one thing in mind strings have only 1 and 0 .

for example

i have character pointer that stores string like "100110" so its takes 6 bytes to store but i want to store this in bits so i reduce memory occpuied.

Upvotes: 4

Views: 682

Answers (4)

NalaGinrut
NalaGinrut

Reputation: 74

Why not use 'strtol'? It's a standard lib function. Or you're writing low-level code for memory shortage hardware?

char *str = "010101";
int i = strtol(str ,(char**)NULL ,2);

==> i=21

Upvotes: 0

iammilind
iammilind

Reputation: 69988

One way is to, define that char* [] as a global and use its indices for accessing it:

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

Usage: Instead of

char *p = stringLiteral[3];

use

unsigned int idx = 3;

Rationale: If you are compacting this string into bits for serialization purpose than it's ok. But otherwise I don't see any use case of compacting them. In my above solution, it doesn't use any extra memory. You already have an array of string literals; I am just asking to declare in global scope and use its index.

Also, if the string size is > 32 bytes then, you won't be able to store it in a single 32-bit int.

Upvotes: -1

Simon
Simon

Reputation: 890

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 cannot test this for now, so please correct me if I'm 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')

Upvotes: 3

user149341
user149341

Reputation:

Have you tried the STL bitset container? It's optimized for exactly this purpose. Alternatively, creating a vector of bool elements will internally pack bits to save space.

Upvotes: 3

Related Questions