How to compress a complex number like 0.0332815625326639 + 0.000694052654051097i
into a bit stream and then decode it to get back the same number?
Asked
Active
Viewed 1,067 times
0

Matt
- 12,848
- 2
- 31
- 53

Mohab Mostafa
- 109
- 1
- 8
1 Answers
0
To generate the bitstream, you can use the following approach:
- Separate real and imaginary part.
- Convert the number into its hexadecimal representation with
num2hex
and use each character as one row (transpose it with.'
). - Convert each row to a decimal with
hex2dec
. This is needed for the next step. - Create the binary representation for each decimal with
dec2bin
. We need to set a minimal length of 4 since one character in hex occupies 4 bits. - Put the values of each row after each other. Now we have converted the hex-string into its binary representation of length 64.
- Append the imaginary part after the real part which gives us a bitstream of length 128.
To decode the bitstream and get the number back, you can reverse the steps above:
- Split the bitstream in two junks of length 64. The first is the real part (
1:64
), the second represents the imaginary part (65:128
). - Reshape the string to form rows of four characters.
- Convert the rows to a decimal number with
bin2dec
. - Convert the decimal numbers to their hex-representation with
dec2hex
. - Convert the hexadecimal string back to the original number with
hex2num
. - Use
complex
to get a complex number consisting of the real and imaginary part. You could userealpart+imagpart*i
as well.
Now let's see the code for all of that:
function the_demo
x = 0.0332815625326639 + 0.000694052654051097i;
bitstream = cb_encode(x)
value = cb_decode(bitstream)
check = x-value % see if we succeeded
function bin = cb_encode(x)
a1 = dec2bin(hex2dec(num2hex(real(x)).'),4);
a2 = dec2bin(hex2dec(num2hex(imag(x)).'),4);
bin = [reshape(a1.',1,[]),reshape(a2.',1,[])];
function y = cb_decode(bin)
b1 = reshape(bin(1:64),4,[]).';
b1 = hex2num(dec2hex(bin2dec(b1)).');
b2 = reshape(bin(65:128),4,[]).';
b2 = hex2num(dec2hex(bin2dec(b2)).');
y = complex(b1,b2);
Running this, gives the following output:
>> the_demo
bitstream =
00111111101000010000101001000111111011010100011001101111101000000011111101000110101111100010001010111001101101011000000000110010
value =
0.0333 + 0.0007i
check =
0

Matt
- 12,848
- 2
- 31
- 53