十进制到二进制作为双精度类型数组,而不是字符串
Decimal to binary as double type array, not string
到目前为止我有这个:
data = 14
out = dec2bin(data, 4)
给出:
out = 1110
但是我想得到这种格式的二进制数:
out = [1 1 1 0]
感谢您的帮助!
您正在寻找带有 'left-msb'
选项的 de2bi
。
data = 14
out = de2bi(data, 4,'left-msb')
不过这需要 通信系统工具箱。或者,将您的原始方法与基本 dec2bin
结合使用,并添加以下内容:
data = 14
out = double( dec2bin(data, 4) ) - 48
out =
1 1 1 0
另一种方式:使用"bitget":
data = 14
out = bitget (data, 4:-1:1)
out =
1 1 1 0
它需要 通信系统工具箱。
如果没有,您可以在代码开头定义这些函数:
de2bi = @(x) dec2bin(x)>48;
bi2de = @(x) x*2.^(size(x,2)-1:-1:0)';
测试:
dec = 1:10
bin = de2bi(dec)
dec = bi2de(bin)
输出:
dec =
1 2 3 4 5 6 7 8 9 10
bin =
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
dec =
1
2
3
4
5
6
7
8
9
10
P.S. 如果出于某种原因您不想使用 dec2bin
所有,你可以定义de2bi
函数为:
在Matlab/Octave:
de2bi = @(x) 2.^[(floor(log2(max(x(:)))):-1:1),0];
de2bi = @(x) rem(x(:),2*de2bi(x))>(de2bi(x)-1);
仅在 Octave 中(只要 Octave 允许匿名函数的默认值):
默认情况下 returns 与前面的示例相同,但可选的位位置参数可用:
de2bi = @(dec,bit=[(1+floor(log2(max(dec(:))))):-1:2, 1]) rem(dec(:),2.^bit)>(2.^(bit-1)-1);
%Call examples:
x=0:10;
n=3:-1:1;
de2bi(x)
de2bi(x,n) % returns only the three least significant bits
P.S. 此处提供了更常见的答案:
到目前为止我有这个:
data = 14
out = dec2bin(data, 4)
给出:
out = 1110
但是我想得到这种格式的二进制数:
out = [1 1 1 0]
感谢您的帮助!
您正在寻找带有 'left-msb'
选项的 de2bi
。
data = 14
out = de2bi(data, 4,'left-msb')
不过这需要 通信系统工具箱。或者,将您的原始方法与基本 dec2bin
结合使用,并添加以下内容:
data = 14
out = double( dec2bin(data, 4) ) - 48
out =
1 1 1 0
另一种方式:使用"bitget":
data = 14
out = bitget (data, 4:-1:1)
out =
1 1 1 0
它需要 通信系统工具箱。
如果没有,您可以在代码开头定义这些函数:
de2bi = @(x) dec2bin(x)>48;
bi2de = @(x) x*2.^(size(x,2)-1:-1:0)';
测试:
dec = 1:10
bin = de2bi(dec)
dec = bi2de(bin)
输出:
dec =
1 2 3 4 5 6 7 8 9 10
bin =
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
dec =
1
2
3
4
5
6
7
8
9
10
P.S. 如果出于某种原因您不想使用 dec2bin
所有,你可以定义de2bi
函数为:
在Matlab/Octave:
de2bi = @(x) 2.^[(floor(log2(max(x(:)))):-1:1),0];
de2bi = @(x) rem(x(:),2*de2bi(x))>(de2bi(x)-1);
仅在 Octave 中(只要 Octave 允许匿名函数的默认值):
默认情况下 returns 与前面的示例相同,但可选的位位置参数可用:
de2bi = @(dec,bit=[(1+floor(log2(max(dec(:))))):-1:2, 1]) rem(dec(:),2.^bit)>(2.^(bit-1)-1);
%Call examples:
x=0:10;
n=3:-1:1;
de2bi(x)
de2bi(x,n) % returns only the three least significant bits
P.S. 此处提供了更常见的答案: