【问题标题】:Integer to Byte conversion in Java vs GoJava vs Go 中的整数到字节转换
【发布时间】:2021-11-06 12:40:38
【问题描述】:

我想连接两个服务器应用程序。一种是用 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 方面做错了什么吗?

【问题讨论】:

  • Java 结果是正确的。 1066249 是 0x00104509,在 little-endian 中是 0x09 0x45 0x10 0x00,或 9 69 16 0。

标签: java go integer byte


【解决方案1】:

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

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

这就是link为什么不能使用任意大小值

推荐的方法是处理错误,错误代码给出了失败或意外行为的原因。这是给出与 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 到工作代码

【讨论】:

    猜你喜欢
    • 2015-10-18
    • 2020-02-05
    • 2011-01-28
    • 2012-07-10
    • 1970-01-01
    • 2010-12-28
    • 2015-05-12
    • 1970-01-01
    相关资源
    最近更新 更多