Having problem converting a string to an integer using sscanf
Afficher commentaires plus anciens
Hi all, I'm having an issue converting a string to a number. See a copy of my problem below:
>> b = sscanf('123456789012345678', '%lu')
b =
4.2950e+009
Why is this happening? The same problem occurs all the way down to 10 digits. At 9, it returns the integer as expected. Your help is appreciated.
7 commentaires
Geoff Hayes
le 28 Jan 2020
hiaxis - I get the correct result on my 64-bit mac. What can you tell us about your computer and/or version of MATLAB? If you use computer as
[str,maxsize,endian] = computer
what is the value for each output parameter?
Geoff Hayes
le 28 Jan 2020
hiaxis's answer moved here
Thank you for the fast reply. I am running an old R14 SP3 version of MATLAB under Windows 10. It seems like this is a new problem for me but perhaps I'm remembering wrong. Here are the results of the command you provided:
>> [str,maxsize,endian] = computer
str =
PCWIN
maxsize =
2.1475e+009
endian =
L
Geoff Hayes
le 28 Jan 2020
Could it be that you are running a 32-bit version of MATLAB? From https://www.mathworks.com/matlabcentral/answers/96172-how-can-i-determine-if-i-am-running-a-32-bit-version-of-matlab-or-a-64-bit-version-of-matlab,
OUTPUT OF COMPUTER VERSION OF MATLAB (32 bit / 64 bit)
PCWIN 32 bit MATLAB on Windows
So your output to sscanf may be reasonable given your version of the software...
In my version of matlab, I get a uint64 value out of that sscanf code whereas in the OP case it's clearly double. 4.295e9 is also suspiciously what you get from intmax('uint32') so I suspect that in R14, sscanf is limited to 32-bit integers. Even if it wasn't limited to 32 bit, the conversion to double would round the number to the nearest multiple of 16.
Maybe it's time to upgrade. R14SP3 came out 15 years ago!
hiaxis
le 28 Jan 2020
Guillaume
le 28 Jan 2020
Yes, you could actually store the number if sscanf didn't convert to double. However since 123456789012345678 is greater than flintmax you'd be losing precision anyway (the number will get rounded down to 123456789012345680)
In any case, it does look like sscanf is limited to 32-bit numbers in your case.
Mohammad Sami
le 29 Jan 2020
Can you try textscan ? Do you get the same issue with textscan ?
Réponses (0)
Catégories
En savoir plus sur Data Type Conversion dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!