msgpack-go icon indicating copy to clipboard operation
msgpack-go copied to clipboard

floats need special handling when unpacked

Open dvirsky opened this issue 12 years ago • 0 comments

Packing a float value does not necessarily pack it as a float in the underlying protocol you try to optimize for space. This is not a bug, but it makes for very cumbersome code when unpacking floats, because a float can be encoded either a UInt of some length, or an Int of some length.

Unless I'm missing something (I'm pretty new to Go), you have to decode it as such:

switch value.Kind() {
        case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
            ival := value.Uint()
            fval = *(*float32)(unsafe.Pointer(&ival))
        case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
            ival := value.Int()
            fval = *(*float32)(unsafe.Pointer(&ival))
}

Shouldn't this be handled automatically with something like UnpackFloat32/64() ?

dvirsky avatar Oct 02 '12 08:10 dvirsky