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

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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上