Why no signed conversions in binary.ByteOrder?

168 views
Skip to first unread message

a2800276

unread,
Jul 27, 2024, 5:48:37 AM7/27/24
to golang-nuts
Just out of curiosity, does anyone have a good rationale as to why there are only unsigned conversions available `binary.ByteOrder`? It would seem that this functionality is there to avoid dumb careless errors doing byte order conversions, but this design forces me to have to think about whether I can cast uint64 to int64 without loss of precision ...


wagner riffel

unread,
Jul 27, 2024, 4:13:59 PM7/27/24
to golang-nuts, a2800276
I don't understand how an Int64() method can do any better than int64(x)
conversion, neither how there's loss of precision if both are the same size, and
on any computer I'm aware of both types uses the same bit pattern. So maybe
that's the rationale, use regular uint64 -> int64 langauge conversion.

BR.

-w

a2800276

unread,
Jul 28, 2024, 10:43:06 AM7/28/24
to golang-nuts
I agree it has no technical merit. It can't do better, but it avoid having to think about the type mismatch. The functionality provided by ByteOrder is fairly simple to begin with, I assume its whole purpose is to reduce cognitive load/avoid dumb mistakes. My assumption is that it's probably not immediately obvious to everyone whether `a := int64(unsigned_value)` never loses precision or never reinterprets/reorders the physical value of the bytes. At least I had to stop and think about it and the benefit of a things like ByteOrder would be not having to think :) Then again, I'm not particularly bright.

wagner riffel

unread,
Jul 28, 2024, 3:29:57 PM7/28/24
to a2800276, golang-nuts
a2800276 <a280...@gmail.com> wrote:
> I agree it has no technical merit. It can't do better, but it avoid having
> to think about the type mismatch. The functionality provided by ByteOrder
> is fairly simple to begin with, I assume its whole purpose is to reduce
> cognitive load/avoid dumb mistakes. My assumption is that it's probably not
> immediately obvious to everyone whether `a := int64(unsigned_value)` never
> loses precision or never reinterprets/reorders the physical value of the
> bytes. At least I had to stop and think about it and the benefit of a
> things like ByteOrder would be not having to think :) Then again, I'm not
> particularly bright.
>

This binary package provides Varint (see go doc) encoded integer which detects
overflows. This may help with dumb mistakes if it's easy to switch to its
encoding format.

BR.

-w
Reply all
Reply to author
Forward
0 new messages