Reputation: 3384
I want to hold some binary data in a variable in matlab for example
1 1 1 1 0 0 0 1
Later I want to convert it to hex like this
F1
I am unable to identify that how to hold binary data in a variable and is there a function perform that conversion
Upvotes: 2
Views: 1772
Reputation: 221774
You can use something like this, assuming a
as the input binary row vector -
%// 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')))'
Note that there are no restrictions in it for the number of binary elements in the input vector. So, as a random 1 x 291
sized input binary data, the output was -
out =
02678E51063A7FFBD9CE1DF6A3DC63B17F71C39C17DC499AD58516D7B571FC58DF05957F7
Upvotes: 4
Reputation: 112779
A possibly faster approoach, which makes use of the fact that exactly four binary digits make up a hex digit:
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
Upvotes: 2
Reputation: 1631
There are MATLAB built in functions for your case: logical()
and binaryVectorToHex()
, but, Data Acquisition Toolbox is needed for binaryVectorToHex()
.
Try this:
>> vec = randi(2, 1, 100) - 1; %// Double type vector
>> vecBin = logical(vec); %// Binary conversion
>> vecHex = binaryVectorToHex(vecBin); %// Hexadecimal conversion
Upvotes: 2