我需要将十进制数转换为二进制向量。
例如,像这样:
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]
谢谢
您提到不能使用函数de2bi
,这很可能是因为它是通信系统工具箱中的函数,而您没有许可证。幸运的是,有两个其他函数可供使用,它们是MATLAB核心工具箱的一部分:BITGET和DEC2BIN。我通常倾向于使用BITGET,因为DEC2BIN在同时转换多个值时可能会慢得多。以下是如何使用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
dec2bin
并只是输错了,我甚至不知道 de2bi
真的存在。 - Jonasfliplr(bitget(Data,1:6))
以获得“正确”次序的数字。当然,这取决于使用情况 (: - chessofnerd使用Matlab内置函数dec2bin
只需一次调用即可实现此目的:
binVec = dec2bin(data, nBits)-'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
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];