inconsistency in converting string to integer, when string is hex, prefixed with '0x'

前端 未结 3 434
轻奢々
轻奢々 2021-01-14 05:44

Using PHP 5.3.5. Not sure how this works on other versions.

I\'m confused about using strings that hold numbers, e.g., \'0x4B0\' or \'1.2e3\'

3条回答
  •  被撕碎了的回忆
    2021-01-14 06:20

    The direct casts (int)$str and (float)$str don't really work differently at all: They both read as many characters from the string as they can interpret as a number of the respective type.

    For "0x4B0", the int-conversion reads "0" (OK), then "x" and stops, because it cannot convert "x" into an integer. Likewise for the float-conversion.

    For "1.2e3", the int-conversion reads "1" (OK), then "." and stops. The float-conversion recognises the entire string as valid float notation.

    The automatic type recognition for an expression like $str * 1 is simply more flexible than the explicit casts. The explicit casts require the integers and floats to be in the format produced by %i and %f in printf, essentially.

    Perhaps you can use intval and floatval rather than explicit casts-to-int for more flexibility, though.

    Finally, your question "is hexidecimal data supposed to be valid or invalid numeric data?" is awkward. There is no such thing as "hexadecimal data". Hexadecimal is just a number base. What you can do is take a string like "4B0" and use strtoul etc. to parse it as an integer in any number base between 2 and 36.[Sorry, that was BS. There's no strtoul in PHP. But intval has the equivalent functionality, see above.]

提交回复
热议问题