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.
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');