_byteswap_ulong in Golang

huangapple go评论86阅读模式
英文:

_byteswap_ulong in Golang

问题

在Golang中,_byteswap_ulong的等效函数是什么?是否存在相应的包?

我尝试使用binary包并与reader进行操作,但无法使其正常工作。我需要在uint64变量中交换字节。

输入为2832779。输出应为8b392b。

英文:

What is the equivalent of _byteswap_ulong in Golang?
Does it exist as a package?

I tried to use the binary package and play with the reader, but couldn't get it working. I need to swap bytes in a uint64 variable.

Input is 2832779. Output should be 8b392b.

答案1

得分: 2

包encoding/binary有一个ByteOrder类型
http://golang.org/pkg/encoding/binary/#ByteOrder

binary.LittleEndian和binary.BigEndian可以让你切换到不同的字节顺序。

它并不完全相同,因为它不仅仅交换字节。但可能可以满足你的需求。

英文:

The package encoding/binary has a ByteOrder type
http://golang.org/pkg/encoding/binary/#ByteOrder

binary.LittleEndian

and

binary.BigEndian

Let you swap to different orders.

It's not exactly the same as it doesn't just swap bytes. But may get you what you need.

答案2

得分: 1

Golang 1.9在math/bits包中添加了ReverseBytes函数系列。

package main

import (
	"fmt"
	"math/bits"
)

func main() {
	fmt.Printf("%x", bits.ReverseBytes32(2832779))
}

Playground链接

英文:

Golang 1.9 added ReverseBytes function family in package math/bits.

package main

import (
	"fmt"
	"math/bits"
)

func main() {
	fmt.Printf("%x", bits.ReverseBytes32(2832779))
}

Playground link

答案3

得分: 0

如@David所说,使用binary.ByteOrder类型。

package main

import (
	"encoding/binary"
	"fmt"
)

func main() {
	value := make([]byte, 4)

	// 需要提前知道字节顺序
	binary.LittleEndian.PutUint32(value, 0x12345678)

	fmt.Printf("%#v\n", value)

	fmt.Printf("大端表示法, 0x%X\n", binary.BigEndian.Uint32(value))
	fmt.Printf("小端表示法, 0x%X\n", binary.LittleEndian.Uint32(value))
}

Playground链接

这将输出:

[]byte{0x78, 0x56, 0x34, 0x12}
大端表示法, 0x78563412
小端表示法, 0x12345678

这些是在一个小端服务器上的大端和小端表示法。

英文:

As @David said, use the binary.ByteOrder type

package main

import (
	"encoding/binary"
	"fmt"
)

func main() {
	value := make([]byte, 4)
    
    // need to know the byte ordering ahead of time
	binary.LittleEndian.PutUint32(value, 0x12345678)

	fmt.Printf("%#v\n", value)

	fmt.Printf("Big Endian Representation, 0x%X\n", binary.BigEndian.Uint32(value))
	fmt.Printf("Little Endian Representation, 0x%X\n", binary.LittleEndian.Uint32(value))
}

Playground link

This will output:

[]byte{0x78, 0x56, 0x34, 0x12}
Big Endian Representation, 0x78563412
Little Endian Representation, 0x12345678

These are the big-endian and little-endian representations on a little-endian server.

huangapple
  • 本文由 发表于 2015年5月11日 00:18:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/30153664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定