相关疑难解决方法(0)

interface{} to []byte conversion in golang

I am trying to unmarshal a data which is of type interface. So I need to convert the interface type to []byte and pass it to unmarshall. i tried

  1. err := json.Unmarshal([]byte(kpi), &a) => failed
  2. i tired to convert the interface to byte by using kpidata, res := kpi.([]byte) => failed, kpidata is nil

So is there any way we can convert it?

Example: https://play.golang.org/p/5pqQ0DQ94Dp

json go

12
推荐指数
2
解决办法
2万
查看次数

在go中将int32转换为字节数组

我正在使用big.NewInt(int64(e)).Bytes()将int32转换为字节数组.有没有更优雅的方式来做到这一点?

我希望AQAB是e的base64编码值

http://play.golang.org/p/M46X7OpZpu

const e = 65537

func base64Encode(b []byte) string {
  return strings.TrimRight(base64.StdEncoding.EncodeToString(b), "=")
}

func main() {
  fmt.Printf("exp %d\n", e)

  b := make([]byte, 4)
  binary.BigEndian.PutUint32(b, e)
  fmt.Printf("b: BigEndian.PutUint32 %x (Bad) %s\n", b, base64Encode(b))

  b2 := make([]byte, 4)
  binary.BigEndian.PutUint32(b2, e)
  for i := range b2 {
    if b2[i] != 0 {
    b2 = b2[i:]
    break
     }
  }
  fmt.Printf("b2: BigEndian.PutUint32 %x (Good) %s\n", b2, base64Encode(b2))

  b4 := big.NewInt(int64(e)).Bytes()
  fmt.Printf("b4: big.NewInt(int64(e)).Bytes() %x (Good) %s\n", b4, base64Encode(b4))
}
Run Code Online (Sandbox Code Playgroud)

输出:

exp 65537
b: …
Run Code Online (Sandbox Code Playgroud)

go

10
推荐指数
1
解决办法
5767
查看次数

在 Go 中检查字节顺序的更好方法

我正在编写一个小程序来使用 Go 检查字节序:

var i int = 0x0100
ptr := unsafe.Pointer(&i)
if 0x01 == *(*byte)(ptr) {
    fmt.Println("Big Endian")
} else if 0x00 == *(*byte)(ptr) {
    fmt.Println("Little Endian")
} else {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

import "unsafe"打包转换*int*byte. 但正如https://golang.org/pkg/unsafe/ 中提到的:

包 unsafe 包含绕过 Go 程序类型安全的操作。

导入不安全的包可能是不可移植的,不受 Go 1 兼容性指南的保护。

有没有更好的方法来确定字节序,还是我必须使用不安全的包?

endianness go

8
推荐指数
2
解决办法
4887
查看次数

将int8放入字节数组

我有以下字节数组:

buf := make([]byte, 1)
var value int8
value = 45
buf[0] = value // cannot use type int8 as type []byte in assignment
Run Code Online (Sandbox Code Playgroud)

当我想将一个char值放入字节数组时,我得到了错误cannot use type int8 as type []byte in assignment.怎么了?我该怎么做呢?

go

5
推荐指数
1
解决办法
3167
查看次数

标签 统计

go ×4

endianness ×1

json ×1