limp
limp

Reputation: 929

Convert a hex number to decimal in Matlab

I have something like the following:

92e1a330
3ff32343
4a443455
23d4df43
5323e345

I realised that Matlab is not able to read hex numbers using textscan so I read the whole text file as a string. The problem is that when I try to use hex2dec() to convert the string to hex, I don't quite get what I want. For instance, for 92e1a330 hex, hex2dec returns 2.4643e+009 instead of 2464260912. Is it possible to fix that somehow? Thanks!

Upvotes: 2

Views: 9268

Answers (3)

Xiangrui Li
Xiangrui Li

Reputation: 2436

As others have answered, the number is there, but Matlab omits some digits due to the format setting.

A simple way is to force the result from hex2dec to be integer, and then all digits will show up. For example:

x = uint32(hex2dec('92e1a330'))

x =

2464260912

Upvotes: 0

Pursuit
Pursuit

Reputation: 12345

You can adjust the way Matlab displays numbers, but the actual values are generally stored with more precision than it prints to the screen.

To adjust the display format, use the format command. For example:

>> format short g  %This is the default
>> x = hex2dec('92e1a330')
x =
  2.4643e+009

Now set the format to a long format

>> format long g
>> y = hex2dec('92e1a330')
y =
            2464260912

Regardless, the numbers are the same

>> x-y
ans =
     0

There are a lot of format options, including display as hex, and display as engineering (like scientific, but the exponent is always a multiple of 3). help format for more.

Upvotes: 0

John Colby
John Colby

Reputation: 22588

The full number is there, just hidden behind the display formatting. For example:

num2str(hex2dec('92e1a330'))

ans =

2464260912

Upvotes: 2

Related Questions