Integer to Byte conversion in Java vs Go

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

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<br>
1 = {uint8} 74<br>
2 = {uint8} 16<br>
3 = {uint8} 0<br>


但是,如果我在Java应用程序中做同样的操作,我得到了以下数字:

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

0 = 9<br>
1 = 69<br>
2 = 16<br>
3 = 0<br>

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

英文:

I want to connect two server apps. One is written in Java and the other one in Go. Both communicate via a simple protocol on byte level.

At the Go app I got this result:

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

0 = {uint8} 79<br>
1 = {uint8} 74<br>
2 = {uint8} 16<br>
3 = {uint8} 0<br>


But if I do the same in my Java app, I got this numbers:

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

0 = 9<br>
1 = 69<br>
2 = 16<br>
3 = 0<br>

Does anybody know, what I'm doing wrong on the Java side?

答案1

得分: 4

当我尝试执行你分享的code时,它会给出一个正确的错误信息:

2009/11/10 23:00:00 写入缓冲区时出错,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("写入缓冲区时出错,%s", err.Error())
	}
	fmt.Printf("%v", buf.Bytes())
}

输出结果为:

[9 69 16 0]

这是工作代码的PlayGround链接

英文:

When I try to execute the code you have shared, it gives a proper error message

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

And here is the link why you can not use arbitrary size values

The recommended approach is to handle the error, the error code gives the reason for the failure or the unexpected behavior. Here is the working code that gives same result as java

package main

import (
	&quot;bytes&quot;
	&quot;encoding/binary&quot;
	&quot;fmt&quot;
	&quot;log&quot;
)

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

output

[9 69 16 0]

Here is the PlayGround link to the working code

huangapple
  • 本文由 发表于 2021年9月10日 05:55:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/69125104.html
匿名

发表评论

匿名网友

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

确定