0

How to make a char array containing only digits more efficient?

I have a char array: char* str = "848166184861571848671904971"; Each one of the chars takes 1 byte of memory(8 bits) so 256 values can be stored in a char, but the digits are from 0 to 9, so 10 out of 256 values are actually used, which is less than 4% of the space a char can take. That means a lot of space is not used. I feel like there is a way to compress the string to make it a lot more efficient, but i dont know how and if anyone here could help me i would be very grateful.

15th Jul 2016, 8:58 PM
this->getName()
4 ответов
+ 1
Well, assuming you are with something *like* char, not exactly a char, you could use std::uint8_t from <cstdlib> header. As "standard" char and std::int8_t, std::uint8_t also uses exactly one byte per element (as the type name suggests). Nevertheless, it's not so nice to represent numbers in it, and to initialize it, as you have to initialize the bytes / elements with the less pleasant array initializer: std::uint8_t arr[] ={12, 256, 134, 256}; What that number means requires interpretation but you can figure it out quite easily. This uses every single bit. For old compilers you might have to include <stdlib.h>instead and drop the std::
16th Jul 2016, 12:59 AM
Stefan
Stefan - avatar
0
It basically mean you can save upto 256 values. Doesnt mean it reserves the whole 256 values space. Only the used Size of the Array is reserved. And it also mean the no.of chars in the array. Not the types of chars use. So basically writing up 20 numbers mean 20 out of 256. It counts Characters only.
15th Jul 2016, 9:50 PM
Dunura Dulshan
Dunura Dulshan - avatar
0
Dunura: this is wrong. I can make a char array 256+ chars long.
16th Jul 2016, 6:48 AM
this->getName()
0
Another answer i came up with is this: digits are from 0 to 9, and 9 in binary is 1001, so any digit can be expressed in 4bits and because chars stores up to 8bits that means i could store two digits in a char, one in the first 4 bits of the charband another digits in the remaining 4, so, for example 10000110: first 4 digits express the number 6 and the other one the number 8 so that would be number 68. Anyways, the answer stefan gives is better.
16th Jul 2016, 6:56 AM
this->getName()