How to convert list of binary values to int32 type?

自古美人都是妖i 提交于 2019-12-10 22:17:54

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/52593070/how-to-convert-list-of-binary-values-to-int32-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!