如何将二进制值列表转换为 int32 类型?
How to convert list of binary values to int32 type?
我在 MATLAB 工作区中有一个小端格式的二进制数列表,我想将它们转换为 int32。 a
是零和一的双向量,像这样:
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)
给出了 32 个二进制值的行向量,但没有将其转换为 32 位整数。
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
如果你直接在计算中知道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。
如果 a
是一个 N×32 矩阵,您可以简单地将 sum(...)
替换为链接解决方案中的向量化计算:
b = typecast(uint32(a*(2.^(0:size(a, 2)-1)).'), 'int32');
我在 MATLAB 工作区中有一个小端格式的二进制数列表,我想将它们转换为 int32。 a
是零和一的双向量,像这样:
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)
给出了 32 个二进制值的行向量,但没有将其转换为 32 位整数。
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
如果你直接在计算中知道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。
如果 a
是一个 N×32 矩阵,您可以简单地将 sum(...)
替换为链接解决方案中的向量化计算:
b = typecast(uint32(a*(2.^(0:size(a, 2)-1)).'), 'int32');