我需要将十进制数转换为二进制矢量
例如,像这样的东西:
length=de2bi(length_field,16);
Run Code Online (Sandbox Code Playgroud)
不幸的是,由于许可,我无法使用此命令.是否存在将二进制转换为向量的快速短技术.
这是我要找的,
If
Data=12;
Bin_Vec=Binary_To_Vector(Data,6) should return me
Bin_Vec=[0 0 1 1 0 0]
Run Code Online (Sandbox Code Playgroud)
谢谢
gno*_*ice 18
您提到无法使用该功能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
Run Code Online (Sandbox Code Playgroud)
jas*_*xun 10
只需调用Matlab的内置函数dec2bin即可实现:
binVec = dec2bin(data, nBits)-'0'
Run Code Online (Sandbox Code Playgroud)
这是一个相当快的解决方案:
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
Run Code Online (Sandbox Code Playgroud)
使用:
out = binary2vector(12,6)
out =
0 0 1 1 0 0
out = binary2vector(22,6)
out =
0 1 1 0 1 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21287 次 |
| 最近记录: |