如何在matlab中保存二进制数据并进行十六进制转换

How to hold binary data in matlab and perform hex conversion

例如,我想在 matlab 的变量中保存一些二进制数据

1 1 1 1 0 0 0 1

稍后我想像这样将其转换为十六进制

F1

我无法确定如何将二进制数据保存在变量中,是否有函数执行该转换

你可以使用这样的东西,假设 a 作为输入二进制行向量 -

%// Pad zeros to make number of binary bits in input as multiple of 4
a = [zeros(1,4-mod(numel(a)-1,4)-1) a];

%// Convert to string, then to binary and finally to hex number as a char array
out = dec2hex(bin2dec(num2str(reshape(a,4,[])','%1d')))'

请注意,没有限制输入向量中二进制元素的数量。因此,作为随机 1 x 291 大小的输入二进制数据,输出为 -

out =
02678E51063A7FFBD9CE1DF6A3DC63B17F71C39C17DC499AD58516D7B571FC58DF05957F7

您的案例有 MATLAB 内置函数:logical() and binaryVectorToHex(),但是,binaryVectorToHex().

需要 Data Acquisition Toolbox

试试这个:

>> vec    = randi(2, 1, 100) - 1;      %// Double type vector
>> vecBin = logical(vec);              %// Binary conversion
>> vecHex = binaryVectorToHex(vecBin); %// Hexadecimal conversion

一种可能更快的方法,它利用了恰好四个二进制数字组成一个十六进制数字这一事实:

x = [zeros(1,4-mod(numel(x)-1,4)-1) x]; %// make length a multiple of 4
k = 2.^(3:-1:0); %// used for converting each group of 4 bits into a number
m = '0123456789ABCDEF'; %// map from those numbers to hex digits
result = m(k*reshape(x,4,[])+1); %// convert each 4 bits into a number and apply map