Domanda

I need to store a string of 8 chars (they're all digits) in a compressed method,

As I understand it, each char uses 8 bits which are 1 byte and since I only use digits I can use 4 bits (2^4=16 combinations) so for each unsigned char I can store two digits instead of one. Thus I need 4 bytes to store 8 digits instead of 8 bytes.

Until here am I right or wrong?

Now how am I storing this data in a string of 4 unsigned chars? I'm not looking for an explicit answer just a kick start to understand the motivation.

È stato utile?

Soluzione

There are three obvious ways to store eight decimal digits in four eight-bit values.

One is to reduce each decimal digit to four bits and to store two four-bit values in eight bits.

Another is to combine each pair of decimal digits to make a number from 0 to 99 and store that number in eight bits.

Another is to combine all eight decimal digits to make a number from 0 to 99999999 and store that in 32 bits, treating the four eight-bit values as one 32-bit integer.

To decide between these, consider what operations you need to perform to encode the value (what arithmetic or bit operations are needed to combine two digits to make the encoded value) and what operations you need to perform to decode the value (given eight bits, how do you get the digits out of them?).

To evaluate this problem, you should know about the basic arithmetic operations and the bit operations such as bit-wise AND and OR, shifting bits, using “masks” with AND operations, and so on. It may also help to know that division and remainder are usually more time-consuming operations than other arithmetic and bit operations on modern computers.

Altri suggerimenti

I prefer you use unsigned int as suggested by harold in comments. In unsigned char[4] you may require additional one char for terminating '\0' character.

Use shifting as you yourself suggested for proper conversion from uchar to uint.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top