2

I have a list of binary numbers in little-endian format in MATLAB workspace, and I want to convert them to int32. a is a double vector of zeroes and ones, like so:

a = [0 0 0 1 1 0 0 1   1 1 1 0 1 0 1 0   0 0 0 1 1 0 0 0   1 1 1 1 1 0 0 0];

int32(a) gives me a row vector of the 32 binary values without converting it to 32 bit integer.

gnovice
  • 125,304
  • 15
  • 256
  • 359
B. Z.
  • 129
  • 11
  • Is `a` a logical or character vector? – gnovice Oct 01 '18 at 14:17
  • its a double vector, I read it in from a file as fread(f,'ubit1'). p.s I am not using 'int32' because I am removing certain parts of the file by a bit pattern. – B. Z. Oct 01 '18 at 14:23
  • You can also calculate the number directly, e.g. by defining once a vector of the binary weights and then multiply it by your vector. If the vector is however in e.g. 2's complement, you can extend by the definition – matanj Oct 01 '18 at 14:53
  • mantanj makes a good point. How should we interpret the [format](https://en.wikipedia.org/wiki/Signed_number_representations) (one's complement, two's complement, offset binary)? – gnovice Oct 01 '18 at 15:30
  • The byte ordering is like this. [2...1][4...3][6...5][8...7]. 8 being the most significant bit and 1 being the least significant bit. [ ] is one byte and ... indicate the 6 other bits in that byte. And if 8 is 0, the number is positive, if 1 its negative. Thank you for suggestion, I will create a vector with the weights and multiply it. – B. Z. Oct 01 '18 at 16:35
  • Related: [How can I convert a binary to a decimal without using a loop?](https://stackoverflow.com/q/1552966/52738) – gnovice Oct 02 '18 at 03:06

1 Answers1

5

The solutions from this related question (which is specific to unsigned integers) can be modified to handle a signed integer. The easiest approach would be to convert the output from there to uint32, then convert to int32 using typecast. Building on this solution:

>> a = [0 0 0 1 1 0 0 1 1 1 1 0 1 0 1 0 0 0 0 1 1 0 0 0 1 1 1 1 1 0 0 0];
>> b = typecast(uint32(sum(pow2(find(a)-1))), 'int32')

b =

  int32

   521688984

If you know the specific representation used for the bit pattern (my guess would be two's complement), you could avoid using typecast by accounting for the sign bit and complement directly in the calculations.

If a is an N-by-32 matrix, you can simply replace the sum(...) with the vectorized calculations from the linked solution:

b = typecast(uint32(a*(2.^(0:size(a, 2)-1)).'), 'int32');
gnovice
  • 125,304
  • 15
  • 256
  • 359