将一对整数打包并解压缩为十六进制

时间:2016-02-25 17:50:36

标签: ruby pack unpack

我有一对Little-Endian格式的32位整数,我必须转换为十六进制值并反转过程。 我知道如何转换为十六进制但我有问题转回整数。

h = [15325,24748]

i = h.pack("S*").unpack('N*').first
 => 3711675488 

hex-value = i.to_s(16)
 => "dd3bac60" 

现在,我怎样才能改变" dd3bac60"回到[15325,24748]?

由于

1 个答案:

答案 0 :(得分:1)

只需按相反的顺序执行所有操作,并反转您的打包/解包逻辑:

    class MyApp:
        def __init__(self, parent):
            self.parent = parent
            self.mainFrame = Frame(parent, padx=10, pady=10)
            self.mainFrame.pack(side=TOP, anchor=CENTER)

            parent.bind_class("Menubutton", "<Down>",
                              lambda event: self.menu_MacGyver(event))

            self.report_format = StringVar()
            self.report_format.set("Non-spreadsheet overload report")
            self.base_case_rating = StringVar()
            self.base_case_rating.set("Rate B")
            self.contingency_rating = StringVar()
            self.contingency_rating.set("Rate B")

            self.report_format_options_str = ["Spreadsheet overload report",
                                              "Spreadsheet loading table",
                                              "Available capacity table",
                                              "Non-spreadsheet overload report",
                                              "Non-spreadsheet loading table",
                                              "Non-converged network",
                                              "Non-spreadsheet corrective actions"]
            option1 = OptionMenu(self.mainFrame,
                                 self.report_format,
                                 *self.report_format_options_str)
            option1.config(takefocus=1)
            option1.pack(side=TOP, anchor=NW)

            self.rating_options_str = ["Rate A", "Rate B", "Rate C"]
            option2 = OptionMenu(self.mainFrame,
                                 self.base_case_rating,
                                 *self.rating_options_str)
            option2.config(takefocus=1)
            option2.pack(side=TOP, anchor=NW)

            option3 = OptionMenu(self.mainFrame,
                                 self.contingency_rating,
                                 *self.rating_options_str)
            option3.config(takefocus=1)
            option3.pack(side=BOTTOM, anchor=NW)

        def menu_MacGyver(self, event):
            event.widget.event_generate("<space>")
            event.widget.config(takefocus=0)
            event.widget.focus_set()
            event.widget.config(takefocus=1)

    root = Tk()
    GUI = MyApp(root)
    root.mainloop()

说明:在正向变换中应用的每个函数都有一个反函数,因此只需按相反的顺序应用它们:

  • hex_string = "dd3bac60" [hex_string.to_i(16)].pack('N*').unpack('S*') => [15325, 24748] String#to_i( base )
  • 相反
  • Integer.to_s( base )Array#pack('N*')
  • 相反
  • String#unpack('N*')String#unpack('S*')
  • 相反