Thanks rob, that works, although I would have prefered a solution without unsafe. I found a thread from a few years back where someone proposed adding NativeEndian to encoding/binary which would always do the right thing. Too bad that never got anywhere.
Chris On Thu, Aug 24, 2017 at 08:40:12AM +1000, Rob Pike wrote: > Apologies, typo. This is it: https://play.golang.org/p/9XWoCiUH2D > > On Thu, Aug 24, 2017 at 8:39 AM, Rob Pike <[email protected]> wrote: > > I believe there is no safe (that is, unsafe-free) way to discover the > > native byte order. In a sense, this is because depending on the native > > byte order is intrinsically unsafe. It is by definition not portable. > > It is a terrible design decision. > > > > By the way, that program may work but it's not sound. It has a hidden > > assumption about how bytes are laid out in arrays and the > > correspondence with words. (Some machines, like the PDP-11, actually > > confused some matters like this). This is a better way to discover the > > byte order, at which point you can use portable methods from > > encoding/binary: https://play.golang.org/p/7svQ66wl7I > > > > -rob > > > > On Thu, Aug 24, 2017 at 8:24 AM, <[email protected]> wrote: > >> It use unsafe, but works even in playground: > >> https://play.golang.org/p/S1rw157M9C > >> > >> > >> On Wednesday, August 23, 2017 at 3:49:39 PM UTC+3, Christian von Kietzell > >> wrote: > >>> > >>> Hi, > >>> > >>> I've stumbled across a problem I don't know how to solve. > >>> > >>> I'm trying to read (from stdin) four bytes into a uint32 value. Those > >>> bytes are provided in _native_ byte order by an external program.[*1] > >>> > >>> Since I've found nothing in the standard library to determine the > >>> machine's native byte order I can't decide whether to use > >>> binary.BigEndian.Uint32 or binary.LittleEndian.Uint32. > >>> > >>> Is there a way without involving package unsafe? Am I missing something > >>> obvious? > >>> > >>> [*1] The data comes from a web browser extension using the native > >>> messaging API, which specifies that messages sent to external programs > >>> are prefixed with the 32-bit length of the message in native byte order. > >>> > >>> > >>> Thanks, > >>> Chris > >>> > >>> -- > >>> Nothing to see here. Move along. > >> > >> -- > >> 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 [email protected]. > >> For more options, visit https://groups.google.com/d/optout. -- Nothing to see here. Move along. -- 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 [email protected]. For more options, visit https://groups.google.com/d/optout.
