我是一个char数组,通过在两个char数组之间执行strcat来定义:
coeficientes = strcat(coef_bin, coef_bin_comp)
然后,我想读取每一行并将它们转换为十六进制。我这样做:
for k=1:11
coef_binario = coeficientes(1+(k-1)*8:k*8);
coef_hexadecimal = binaryVectorToHex( coef_binario - '0' );
fprintf('%s\t%s\n', coef_binario, coef_hexadecimal);
end
如果我同时打印coeficientes
变量和每个coef_binario
转换,结果如下:
注意:coeficientes
只是在strcat行后删除分号打印,但coef_binario
使用fprintf
打印,如上所述。
coeficientes =
00011111 00111101 01001100 01011011 01111001 10001000 10010111
10110101 11000100 11010011 11110001
00000111 07 11100111 E7 00011101 1D
00100100 24 11101101 ED 10111111 BF
11000001 C1 11000111 C7 00100100 24
10010110 96 11011011 DB
正如您所看到的,我尝试使用以下方式逐行阅读coeficientes
var:
coef_binario = coeficientes(1+(k-1)*8:k*8);
但是当它被打印时,二进制代码与原始代码不匹配。任何关于为什么或如何才能正确使用它的想法?
更新1
如果我在尝试之前尝试拆分它,为了在我需要获取字符串之前使用strsplit
。我试过了:
strs = strsplit(sprintf('%s', coeficientes), ' ')
由此,我再次获得了错误的链。事实上,在使用sprintf
(而非strsplit
)后,我得到的是:
0000011111100111000111010010010011101101101111111100000111000111001001001001011011011011
更新2
如何生成coeficientes
:
% coef_k is a vector of decimal numbers, i.e.: [1 3 5 8 11 14]
coef_bin = dec2bin(coef_k);
coef_complementario = 16 - coef_k;
coef_bin_comp = dec2bin(coef_complementario);
coeficientes = strcat(coef_bin, coef_bin_comp)
答案 0 :(得分:3)
当前的问题是MATLAB以列主要顺序存储数据,所以基本上发生的事情是,如果您的数据是2D字符数组(dec2bin
的输出):
c = ['00011111'
'00111101'
'01001100'
'01011011'
'01111001'
'10001000'
'10010111'
'10110101'
'11000100'
'11010011'
'11110001'];
然后,当您使用类似1+(k-1)*8:k*8
的线性索引时,它会读取向下列而不是您想要的行。
例如k = 1
:
k = 1;
c(1+(k-1)*8:k*8)
% 00000111 <---- Clearly not the first row. It is the first 8 entries going
% down the first column.
您有四种选择:
在处理之前转置c
(以使数字在列中向下移动):
c = c.';
k = 1;
c(1+(k-1)*8:k*8)
% 00011111 <---- The first row like you would expect!
调整索引表达式以改为列
k = 1;
c(k:size(c,1):end)
% 00011111 <---- The first row like you would expect!
只需使用普通矩阵索引来抓取一行
k = 1;
c(k,:)
% 00011111 <---- The first row like you would expect!
只需使用内置的bin2dec
后跟dec2hex
即可获得十六进制表示。如果将2D字符数组传递给bin2dec
,它会将每个行解释为不同的二进制数。
hex = dec2hex(bin2dec(c));
1F
3D
4C
5B
79
88
97
B5
C4
D3
F1
答案 1 :(得分:1)
使用strsplit
分隔输入字符串,使用空格作为分隔符(在R2013a +中可用,否则使用例如regexp
)。您还可以将for
循环替换为cellfun
以使其更紧凑:
coeff = '00011111 00111101 01001100 01011011 01111001 10001000 10010111 10110101 11000100 11010011 11110001';
strs = strsplit(coeff, ' ');
hex = cellfun(@(str) binaryVectorToHex(str-'0'), strs, 'uni', false);
>> hex
hex =
'1F' '3D' '4C' '5B' '79' '88' '97' 'B5' 'C4' 'D3' 'F1'
<强>更新强>
使用您的输入(字符矩阵),您甚至不需要strsplit
。只需使用@Suever提议的bin2dec
和dec2hex
的组合。您可能还希望使用cellstr
将结果十六进制值包装到单个单元格中。
cellstr(dec2hex(bin2dec(coeficientes)))