Java 与 Go 中的整数到字节的转换

Integer to Byte conversion in Java vs Go

我想连接两个服务器应用程序。一个是用 Java 写的,另一个是用 Go 写的。两者都通过字节级别的简单协议进行通信。

在 Go 应用程序中我得到了这个结果:

buf := bytes.NewBuffer(make([]byte, 0, 17)
binary.Write(buf, binary.LittleEndian, 1066249)

0 = {uint8} 79
1 = {uint8} 74
2 = {uint8} 16
3 = {uint8} 0


但是如果我在我的 Java 应用程序中做同样的事情,我会得到这个数字:

byte[] result = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE).order(ByteOrder.LITTLE_ENDIAN).putInt(1066249).array();

0 = 9
1 = 69
2 = 16
3 = 0

有人知道我在 Java 方面做错了什么吗?

当我尝试执行您分享的 code 时,它给出了正确的错误消息

2009/11/10 23:00:00 Error writing to the buffer, binary.Write: invalid type int

这里是 为什么你不能使用任意大小的值

推荐的方法是处理错误,错误代码给出失败或意外行为的原因。这是给出与 java

相同结果的工作代码
package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
    "log"
)

    func main() {
        buf := &bytes.Buffer{}
        var data int32 = 1066249
        err := binary.Write(buf, binary.LittleEndian, data)
        if err != nil {
            log.Fatalf("Error writing to the buffer, %s", err.Error())
        }
        fmt.Printf("%v", buf.Bytes())
    }

输出

[9 69 16 0]

这是 PlayGround link 的工作代码