How to correctly add \x into string to get the correct conversion of hex value to int or float

I have pasted my codes in the playground in this link Go Playground - The Go Programming Language. My problem is that when I concat the string parts like this long2ComplimentHex := “\x” + completeString[0:2] + “\x” + completeString[2:4] + “\x” + completeString[4:6] + “\x” + completeString[6:8]. The \x gets counted as part of the value. I need this to enable the proper conversion into negative or positive numbers? How can I do a proper concat process to avoid this extra value ?

You should probably build your slice of bytes using strconv.ParseUint(completeString[i:i+2],16,8) instead of trying to hack a hex literal into a string.

Hi Jeff,
I dont quite get you are you saying that I should do this long2ComplimentHex := strconv.ParseUint(completeString[0:0+2], 16, 8) ?

Something like this:

 long2ComplimentByte := make([]byte,len(completeString)/2)
 for i:=0;i<len(completeString);i++ {
  b,err := strconv.ParseUint(completeString[i:i+2],16,8)
  if err!=nil {
    log.Fatalf("bad hex: %s", err)
  }
  long2ComplimentByte[i/2] = b
}

I tried your codes but at this line I get this error cannot use b (variable of type uint64) as type byte in assignment

It was untested code off the top of my head. Add a uint8 type conversion in the next to last line.

https://go.dev/tour/basics/13

Hi Jeff,
Thank you for the benefits of anybody in future here is the complete snippet. I have made some changes to your codes to cater the string to just 4 first bytes.

long2ComplimentByte := make([]byte, 4)
	for i := 0; i < 8; i = i + 2 {
		b, err := strconv.ParseUint(completeString[i:i+2], 16, 8)
		if err != nil {
			log.Fatalf("bad hex: %s", err)
		}
		long2ComplimentByte[i/2] = uint8(b)
	}

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