0

I am attempting to port some Python code over to Go.

In my Python code I do:

print(b"\x02" + (3).to_bytes(4, "big", signed=True))

This returns me []byte{0x2, 0x0, 0x0, 0x0, 0x3}

This adds 2 to the start of my byte array and then 3 on the end with a prefix of 3 0's.

In GO I'm doing

digest = append(digest, byte(0x02))
    err := binary.Write(buf, binary.BigEndian, int64(3))
    if err != nil {
        return nil, err
    }
digest = append(digest, buf.Bytes()...)
return digest

This returns []byte{0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3}

In Python I can choose the length which seems to be the issue, is there something similar in Go when converting an int to bytes?

Thanks!

3
  • 5
    8 byte is used for int64, you can use int32 for 4 byte. You will find details here golang.org/pkg/builtin Commented May 18, 2020 at 16:11
  • 3
    a 64 bit value is 8 bytes. If you only want 4 bytes, use a 32bit value. Commented May 18, 2020 at 16:11
  • Thanks both! If you'd like to add this an answer I'll accept. Commented May 20, 2020 at 10:05

1 Answer 1

1

Like suggested in some comments, too, you can just use a different data type e.g. int32 instead of int64.

digest = append(digest, byte(0x02))
    err := binary.Write(buf, binary.BigEndian, int32(3))
    if err != nil {
        return nil, err
    }
digest = append(digest, buf.Bytes()...)
return digest

This will produce the desired outcome []byte{0x2, 0x0, 0x0, 0x0, 0x3}.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.