dsf11t5u1651 2018-11-25 13:49
浏览 219
已采纳

golang与PHP / Ruby的unpack(“ C *”,。)等效吗?

Been searching around, still new to golang, PHP and ruby have an unpack function that unpacks a binary into an array. I'm trying to figure out how to do the following in golang.

$test = "\01\00\02\03";
print_r(unpack("C*", $test)); // [1,0,2,3]

Or

s = "\01\00\02\03"
arr = s.unpack("C*")
p(arr) # [1,0,2,3]

What's the best approach to doing this using golang?

  • 写回答

1条回答 默认 最新

  • dongye1912 2018-11-25 14:01
    关注

    Please note first that your PHP string of "\01\00\02\03" is a string consisting of the 4 bytes \x01,\x00, \x02, \x03 since the "\01" are interpreted as octal. See the documentation for double quoted strings for details.

    In Go the syntax \01 is not correct. As in C an octal sequence is required to have 3 digits, i.e. \001. Thus, the PHP string "\01\00\02\03" is in Go "\001\000\002\003" (which would also work in PHP). With this in mind unpacking is easy and no special function like unpack is needed for this:

    package main
    import "fmt"
    func main() {
        s := "\001\000\002\003"
        b := []byte(s)
        fmt.Print(b)
    }
    

    Output:

    [1 0 2 3]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?