简体   繁体   中英

How to encode/decode complex number to bitstream in MATLAB?

如何将像0.0332815625326639 + 0.000694052654051097i这样的复数压缩为比特流,然后对其进行解码以获取相同的数字?

To generate the bitstream , you can use the following approach:

  1. Separate real and imaginary part.
  2. Convert the number into its hexadecimal representation with num2hex and use each character as one row (transpose it with .' ).
  3. Convert each row to a decimal with hex2dec . This is needed for the next step.
  4. 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.
  5. Put the values of each row after each other. Now we have converted the hex-string into its binary representation of length 64.
  6. 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:

  1. 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 ).
  2. Reshape the string to form rows of four characters.
  3. Convert the rows to a decimal number with bin2dec .
  4. Convert the decimal numbers to their hex-representation with dec2hex .
  5. Convert the hexadecimal string back to the original number with hex2num .
  6. Use complex to get a complex number consisting of the real and imaginary part. You could use realpart+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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM