+ 3
how to compress byte array in C ?
I have Array of byte ( byte a[] = {'1', '2', 'A', 'F', '5', 'C'}; after compress it must be a[] = {0x12, 0xAF, 0x5C}; how can i do this in C
2 Answers
+ 2
Here some code I wrote quickly, if you need it: https://code.sololearn.com/cf956StsJ8oO/#cpp
+ 1
One byte consists of 8 bits, which we also can represent as 2 hex digits, because 4 bits match exactly one hex digit.
e.g. 0100 1100 (dual) = 4C (hex)
Now if we have numbers, that can be represented with 4 bits (numbers from 0 to 15 in decimal or 0x00 to 0x0F in hexadecimal), we can save both of them in a single byte.
But how we are going to do this? There are probably many solutions but I think the easiest approach is to shift one of the numbers 4 digits to the left and then bitwise OR this number with the other number.
So let's try it:
2 numbers from 0 to 15, lets say (4 and 12)
deci dual-byte hexa-byte
4 0000 0100 04
12 0000 1100 0C
now shift the 4, 4 binary digits to the left (multiply with 2^4 = 16):
64 0100 0000 40
12 0000 1100 0C
and now bitwise OR the two bytes ( or in this setting simply add)
76 1000 1100 4C
This is now the result of saving two numbers in one byte.
If you want to read the two compressed bytes you have to reverse the steps we did to compress them.