how read binary data in go?(smartcard) convert code to java

Giacomo :

I need convert the following code to Java programming language. What does mean []byte{}? What is type uint8?

func int8ToByte(int_val int) byte {
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.LittleEndian, uint8(int_val))
    if err != nil {
        log.Fatal("binary.Write failed:", err)
    }
    return buf.Bytes()[0]
}
icza :

[]byte{} is a composite literal which creates an empty byte slice (of type []byte). The uint8 type is an unsigned integer type whose size is 1 byte. In Go the type byte is an alias for uint8, so byte and uint8 are equivalent and completely interchangeable.

I don't know who wrote your int8ToByte() function, but that seems like an obfuscation. All it does is it returns the least significant byte of its argument, which is nothing more than a simple conversion from int to byte:

byte(int_val)

See this Go example:

func main() {
    fmt.Println(int8ToByte(0x01))
    fmt.Println(int8ToByte(0x0102))
    fmt.Println(int8ToByte(-1))

    var i int
    i = 0x01
    fmt.Println(byte(i))
    i = 0x0102
    fmt.Println(byte(i))
    i = -1
    fmt.Println(byte(i))
}

func int8ToByte(int_val int) byte {
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.LittleEndian, uint8(int_val))
    if err != nil {
        log.Fatal("binary.Write failed:", err)
    }
    return buf.Bytes()[0]
}

It outputs (try it on the Go Playground):

1
2
255
1
2
255

To achieve the same in Java, you again just have to convert the int number to byte:

 public static void main(String []args){
    int i = 0x01;
    System.out.println((byte)i);
    i = 0x0102;
    System.out.println((byte)i);
    i = -1;
    System.out.println((byte)i + " " + String.format("%x", (byte)i));
 }

This outputs:

1
2
-1 ff

Note the difference: Java's byte is signed, it has a valid range of -128..127, while Go's byte is unsigned, its valid range is 0..255. But the binary representation of both outputs are the same. For details, see Java vs. Golang for HOTP (rfc-4226).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=367091&siteId=1