2

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

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

13 Comments

If I want to do this operation only on a single vector
@User1551892 Then use a use directly, where a would be your single vector.
Now, this approach works for even longer vector. I've examined it for 100 of length vector a and gives the same result with binaryVectorToHex(). For information purposes (only)...
@mehmet Exactly! I did the same to double-check! Hope mathworks guys don't sue us now ;)
Thanks alot for both of you in order to help me. Have a nice time.
|
2

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

4 Comments

I do not have data acquisition tool kit. Therefore I can not access method binaryVectorHex method
No keep it. Because it can help some one.
Looks like an useful function actually!
Thanks to both of you. I had forgotten about futher visitor because of same problem.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.