Converting byte array to signed int

Hi,
I have for example the following codes. What it does it take the hex string convert into byte array then I would like to convert to its relevant int value. The issue it doesnt give the signed version of the integer. In this case the value should be -12269766 but I keep getting as 1717974068. How to get the signed version ?

package main

import (
	"encoding/binary"
	"fmt"
)

func main() {
	
	str := "ff44c73a"
	data := []byte(str)
	fmt.Println(data)

	a := binary.BigEndian.Uint32(data)
	// If you need int64:
	a2 := int32(a)
	fmt.Println(a2)

}

The string "ff44c73a" is a sequence of 8 UTF8-encoded characters which can be represented in hexadecimal as: 0x66 0x66 0x34 0x34 0x63 0x37 0x33 0x61. If you want the characters to be interpreted as hexadecimal, then they must be escaped with \x, like: "\xff\x44\xc7\x3a", which produces -12269766 when decoded with binary.BigEndian and converted to an int32: Go Playground - The Go Programming Language

Hi Skillian,
Thank you will try your solution. Just curious with this line a := binary.BigEndian.Uint32(data) what it does it convert it to unsigned integer right ? Then how this line a2 := int32(a) makes it signed ?

Converting between signed and unsigned integer types in Go essentially copies the bits of the source value and “relabels” them into the target type. That is, the actual bits in memory (or in CPU registers) of uint32(4282697530) and int32(-12269766) are the same. Just like uint32(0xffffffff) and int32(-1) are the same. This is because the Go language specification requires that signed integer arithmetic uses two’s complement arithmetic.

Hi Skillian,
Ok I am very clear now. Slowly I am picking up golang.

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