4

I am very new to matlab. I want to store hexadecimal values in array like this

P=[0x96,0x97,0x98];

But I surfed on google I got no solution for it So first I converted this hexadecimal into decimal so I got array like this

P=[150,151,152];

Now I am trying to get hexadecimal value of values of P array.

I tried

P=[dec2hex(150),dec2hex(151),dec2hex(152)];

But when I am trying to print P(1) then instead of 96 I got only 9. I am not understanding this part. How can I get correct result? Please help me.

3 Answers 3

4

Matlab stores hexadecimal number as character arrays (or strings).

So

a = dec2hex(150)

returns:

a = '96'

concatenating hexadecimal strings as you do:

P=[dec2hex(150),dec2hex(151),dec2hex(152)]

returns:

P = '969798'

Therefore, P(1) = '9'

You probably want to use cell arrays to separately store hex-numbers:

P = {dec2hex(150),dec2hex(151),dec2hex(152)};
P{1}

returns:

P = '96'

to retrieve the numeric value, use

hex2dec(P{1})
Sign up to request clarification or add additional context in comments.

1 Comment

But hex2num does not give same answer. Instead we can use str2num(P{1}) to retrive number
2

See manual for dec2hex

dec2hex - Convert decimal to hexadecimal number in string

You are getting a string and thus P(1) only gives you the first character of the string.

Try something like:

>> P=[dec2hex(150);dec2hex(151);dec2hex(152)]; % note the ; instead of ,
>> P

P =

96
97
98

>> P(1,:)

ans =

96

However, P is still an array of characters.

Comments

2

You can use arrayfun with dec2hex to work on them elementwise and produce a cell array as the output that uses the format 0x... -

P=[150,151,152] %// Input array
out = arrayfun(@(n) strcat('0x',dec2hex(P(n))),1:numel(P),'Uni',0)

Code run -

out = 
    '0x96'    '0x97'    '0x98'

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.