Matlab 将十进制转换为二进制向量

Matlab 将十进制转换为二进制向量,matlab,binary,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] 谢谢这里有一个相当快的解决方案: function out = binary2vector(data

我需要把十进制数转换成二进制向量

例如,类似这样的内容:

  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]

谢谢

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

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

您提到无法使用该函数,这可能是因为它是中的函数,并且您没有该函数的许可证。幸运的是,还有两个函数可以使用,它们是核心MATLAB工具箱的一部分:和。我通常倾向于使用BITGET。以下是如何使用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

只需调用Matlab的内置函数
dec2bin
即可实现以下功能:

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

您是否将此用于IEEE 802.11信号字段?我注意到“长度字段”和“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];

非常感谢您的时间和及时的帮助。@kirancshet:不客气。我添加了一点输入测试来避免无限循环。哦,很好+1了解Matlab:)。注意,我认为作者不能使用dec2bin,只是输入错误。我甚至不知道
de2bi
实际上存在。+1便于使用!但是,请注意,许多人希望调用
fliplr(bitget(Data,1:6))
以获得“正确”顺序的数字。当然取决于用法(:非常感谢,我不知道dec2bin可以用来获得这样的二进制向量。可能是