String to []byte conversion

Why am I getting hex string to byte array conversion in golang diffferent from java ?

For hex string - 4CB178CC3FB92FB8693D31F1A39DB8C9

Java byte array - [76 -79 120 -52 63 -71 47 -72 105 61 49 -15 -93 -99 -72 -55]

Golang byte array - [76 177 120 204 63 185 47 184 105 61 49 241 163 157 184 201]
(I am using hex.DecodeString function from encoding/hex for golang)

I want to get the same java byte array in golang. Can anybody help ?

Java uses signed bytes, while Go uses unsigned bytes, but they are exactly the same in different representation (notice how 177 + 79 = 256, to give an example).

The questions are: what do you need to do with them and why is printed format important?

Check the java conversion because Go is doing well. Say B1=177.

Java is doing well too, it only users a different representation. Go uses an uint8 for bytes, while Java uses int8 for them. See this example, it’ll show you they are the same (and also a way to print a byte the “java way” if you need to):

package main

import (
	"fmt"
)

func main() {
	var goByte byte = 177
	var javaByte = int8(goByte)
	fmt.Println(goByte)
	fmt.Println(javaByte)
}

Or check it at the playground: https://play.golang.org/p/JXPUkCFT9Vo.

I want to do 3DES encrytion. I am using Go and the results differ from Java(actual code) becasue od different byte value. Is there a way I can get the same byte array in go as java ?

I’ll insist that they don’t differ, they are exactly the same array of bytes. But if you really, really need to represent them in the same way, just cast bytes to int8s as shown in my previous answer.

1 Like

Yes got it. Thanks you for the valuable suggestion. Thanks to others also.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.