Xor-ing a hex data in go

Hello gophers, happy 4th of July to you all. I am new to the goland and have struggled with this for a couple of hours already. Basically I am trying to write a method to XOR hex data.

00 xor 31 = 31
31 xor 30 = 01
01 xor 2E = 2F
2F xor 03 = 2C

[31, 30, 01, 2F, 03] should yield this 31 01 2F 2C

Any help would be appreciated. Thanks a million

I have looked at the go hex module and several other modules out there but none of them provide a clean way to do the job. I am surely missing something especially because I am super green in golang.

If I get what you are trying to do, you want to start with 0x00 and then sequentially XOR it against [31, 30, 2E, 2C], where in each step you take the result of the last operation and then XOR it with the next element, right?

In that case, something like this should work (it assumes you receive hexs as strings, and that you want to print them as string as well, as that’s how you are showing them, but it’s easily adaptable):

package main

import (
	"fmt"
	"strconv"
)

func main() {
	hexs := []string{"31", "30", "2E", "03"}
	xored := make([]int64, len(hexs))
	for i:= 0; i < len(hexs); i++ {
		dec, err := strconv.ParseInt("0x" + hexs[i], 0, 64)
		if err != nil {
			panic(err)
		}
		if i == 0 {
			xored[i] = dec ^ 0
		} else {
			xored[i] = dec ^ xored[i-1]
		}
		
	}
	for i := 0; i < len(xored); i ++ {
		fmt.Printf("%x\n", xored[i])
	}
}

You may try it at the playground: https://play.golang.org/p/n-SsLiTsQJg

That is exactly correct. Problem solved.

1 Like

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