将十进制转换为二进制矢量

时间:2011-04-21 13:12:11

标签: matlab binary

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

例如,像这样:

  length=de2bi(length_field,16);

不幸的是,由于许可,我无法使用此命令。是否存在将二进制转换为向量的快速简短技术。

以下是我要找的内容,

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

由于

4 个答案:

答案 0 :(得分:18)

您提到无法使用de2bi功能,这很可能是因为它是Communications System Toolbox中的一个功能而您没有许可证。幸运的是,您可以使用另外两个功能,它们是核心MATLAB工具箱的一部分:BITGETDEC2BIN。我通常倾向于使用BITGET DEC2BIN can be significantly slower when converting many values at once。以下是使用BITGET的方法:

>> Data = 12;                  %# A decimal number
>> Bin_Vec = bitget(Data,1:6)  %# Get the values for bits 1 through 6

Bin_Vec =

     0     0     1     1     0     0

答案 1 :(得分:9)

单次调用Matlab的内置函数dec2bin可以实现这一目的:

binVec = dec2bin(data, nBits)-'0'

答案 2 :(得分:7)

这是一个相当快的解决方案:

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

答案 3 :(得分:2)

您是否将此用于IEEE 802.11 SIGNAL字段?我注意到" length_field"和" 16"。 不管怎么说,我是怎么做到的。

    function [Ibase2]= Convert10to2(Ibase10,n)

    % Convert the integral part by successive divisions by 2
    Ibase2=[];


    if (Ibase10~=0)

    while (Ibase10>0)

    q=fix(Ibase10/2);
    r=Ibase10-2*q;
    Ibase2=[r Ibase2];
    Ibase10=q;
    end


    else
    Ibase2=0;
    end

    o = length(Ibase2);
    % append redundant zeros
    Ibase2 = [zeros(1,n-o) Ibase2];
相关问题