Help converting a function

Hi. Could anyone help me converting this Java function to GO?

public long complementOfTo(String hex){
        HexToBin hextobin = new HexToBin();
        long coord = 0;
        int a = Integer.parseInt(String.valueOf(hextobin.hexToBin(hex).charAt(0)));
        switch (a){
            case 0:
                coord = Long.parseLong(hex,16);
            case 1:
                long c = Long.parseLong(hex,16);
                long r = c ^ (long)(Math.pow(2, Math.ceil(Math.log(c)/Math.log(2))) -1);
                coord = Long.parseLong("-".concat(String.valueOf(r)));
        return coord;

Any help is appreciated. Tnx.

Most of this function should be rather straightforward to convert if you know Go. At which part of the code did you get stuck?

Interesting line converting a number to a string and then back to a negative integer :stuck_out_tongue:

The switch case takes the first character of the conversion of the hex to bin and converts it to a integer you could really just switch on the first character instead.

HexToBin() converts a hexadecimal number to a binary and if the first digit is a zero I guess it pads it to a certain width. How many digits?

I may be mistaken but the thing the function does is to convert a hexadecimal number in a string into a two’s complement number (most common representation of signed integers on computers)

package main

import (

func complementOfTwo(hex string) int64 {
	coord, _ := strconv.ParseUint(hex, 16, 64)
	return (int64)(coord)

func main() {
	fmt.Println(complementOfTwo("0000000000000001")) //  1
	fmt.Println(complementOfTwo("ffffffffffffffff")) //  -1

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