MATLAB Answers

0

Adding Hexadecimal numbers?

Jed Louise Ledesma さんによって質問されました 2019 年 10 月 17 日
最新アクティビティ Walter Roberson
さんによって 回答されました 2019 年 10 月 17 日
Can someone help me how to add 2 hexadecimal numbers? I would appreciate the help and sentiment.
I tried using: c=dec2hex(hex2dec(a)+hex2dec(b)));
But it didn't work. Is there a correct way to do this?

  0 件のコメント

サインイン to comment.

3 件の回答

Robert U
Answer by Robert U
on 17 Oct 2019
 Accepted Answer

Hi Jed Louise Lesma,
Despite the extra bracket in your code (I removed it), the method you tried should work:
a = '3afb';
b = '2839';
c=dec2hex(hex2dec(a)+hex2dec(b));
Kind regards,
Robert

  3 件のコメント

Hello Robert,
Thank you for replying! Sorry about the extra bracket my eyes were kinda hazy.
Can this code also be used in a gui?
c=dec2hex(hex2dec(a)+hex2dec(b));
I tried inputting it like this:
a = str2double(get(handles.edit1, 'String'));
b = str2double(get(handles.edit2, 'String'));
c = dec2hex(hex2dec(a)+hex2dec(b));
but it responded with this:
Error using hex2dec>hex2decImpl (line 58)
Input to hex2dec should have just 0-9, a-f, or A-F.
Robert U
on 17 Oct 2019
The "hex"-values are supposed to be given as char. Thus the str2double()-command should be deleted.
Kind regards,
Robert
I appreciate what you did.
Thank you!

サインイン to comment.


Steven Lord
Answer by Steven Lord
on 17 Oct 2019

If you're using release R2019b or later, you can enter hexadecimal numbers directly.
>> 0x3afb + 0x2839
ans =
uint16
25396
>> hex2dec('3afb')+hex2dec('2839')
ans =
25396

  0 件のコメント

サインイン to comment.


Walter Roberson
Answer by Walter Roberson
on 17 Oct 2019

If there is a possibility that the user might enter hex values with more than 53 significant bits then you should use sscanf with %lx format instead of hex2dec.

  0 件のコメント

サインイン to comment.



Translated by