On Tue, May 9, 2017 at 2:10 PM, Ed Vielmetti <e...@packet.net> wrote:
>
> Consider the following code snippet, at https://play.golang.org/p/hUUF9O-p-k
>
> Using go 1.8.1 (same thing with current master branch)
>
> package main
> func main() {
>         x := float64(-1)
>         println(uint64(x))
>         println(int64(x))
>         println(uint64(int64(x)))
> }
>
> On ARM64:
> 0
> -1
> 18446744073709551615
>
> On x86:
>
> 18446744073709551615
> -1
> 18446744073709551615
>
>
> The comment from the ARM engineer: "It seems on arm we are using FCVTZU, for
> rounding to unsigned, which is what the code example is doing. Except on x86
> they are rounding to signed int, and then dropping the sign."
>
> I'd like to know what the results are on other non-ARM, non-x86 platforms
> (Power, Z, MIPS) to know what level of variety exists in this result and
> then adjust the code path everywhere to do the right thing.

For the record, the spec says, in
https://golang.org/ref/spec#Conversions: "In all non-constant
conversions involving floating-point or complex values, if the result
type cannot represent the value the conversion succeeds but the result
value is implementation-dependent."  That is the case that applies
here: you are converting a negative floating point number to uint64,
which can not represent a negative value, so the result is
implementation-dependent.  The conversion to int64 works, of course.
And the conversion to int64 and then to uint64 succeeds in converting
to int64, and when converting to uint64 follows a different rule:
"When converting between integer types, if the value is a signed
integer, it is sign extended to implicit infinite precision; otherwise
it is zero extended. It is then truncated to fit in the result type's
size."

So, basically, don't convert a negative floating point number to an
unsigned integer type.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to