如何将二进制值列表转换为int32类型? [英] How to convert list of binary values to int32 type?

查看:471
本文介绍了如何将二进制值列表转换为int32类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MATLAB工作区中有一个以Little-Endian格式表示的二进制数列表,我想将它们转换为int32. a是零和一的双重向量,如下所示:

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)给了我32个二进制值的行向量,而没有将其转换为32位整数.

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

推荐答案

此相关问题的解决方案(这是特定于无符号整数)可以进行修改以处理有符号整数.最简单的方法是将输出从那里转换为 uint32 ,然后使用 int32 : //www.mathworks.com/help/matlab/ref/typecast.html"rel =" noreferrer> typecast .建立在此解决方案上:

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

如果您知道用于位模式的特定表示(我的猜测是二进制补码),则可以通过考虑符号位和<直接在计算中添加href ="https://www.mathworks.com/help/matlab/ref/bitcmp.html" rel ="noreferrer">补全.

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.

如果a是32乘N的矩阵,则可以简单地将sum(...)替换为链接解决方案中的矢量化计算:

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

这篇关于如何将二进制值列表转换为int32类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆