十进制转换为二进制矢量 [英] Convert Decimal to Binary Vector

查看:172
本文介绍了十进制转换为二进制矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个十进制数转换为二进制矢量

I need to convert a Decimal Number to a Binary Vector

例如,事情是这样的:

  length=de2bi(length_field,16);

不幸的是,因为许可,我不能使用此命令。是否有转换二进制的向量的任何快速短的技术。

Unfortunately, because of licensing, I cannot use this command. Is there any quick short technique for converting binary to a vector.

下面是我找的,

If 
Data=12;
Bin_Vec=Binary_To_Vector(Data,6) should return me
Bin_Vec=[0 0 1 1 0 0]

感谢

推荐答案

下面是一个解决方案,是相当快的:

Here's a solution that is reasonably fast:

function out = binary2vector(data,nBits)

powOf2 = 2.^[0:nBits-1];

%# do a tiny bit of error-checking
if data > sum(powOf2)
   error('not enough bits to represent the data')
end

out = false(1,nBits);

ct = nBits;

while data>0
if data >= powOf2(ct)
data = data-powOf2(ct);
out(ct) = true;
end
ct = ct - 1;
end

要使用:

out = binary2vector(12,6)
out =
     0     0     1     1     0     0

out = binary2vector(22,6)
out =
     0     1     1     0     1     0

这篇关于十进制转换为二进制矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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