在 Ruby 中计算 Array pack 结构格式的大小

发布于 2024-10-08 19:56:10 字数 204 浏览 0 评论 0原文

例如dddddd是系统的本机格式,所以我无法确切知道它有多大。

在 python 中我可以这样做:

import struct
print struct.calcsize('ddddd')

它将返回 40。

我如何在 Ruby 中得到这个?

In the case of e.g. ddddd, d is the native format for the system, so I can't know exactly how big it will be.

In python I can do:

import struct
print struct.calcsize('ddddd')

Which will return 40.

How do I get this in Ruby?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

强者自强 2024-10-15 19:56:10

我还没有找到一个内置的方法来做到这一点,但是当我知道我只处理数字格式时,我已经成功地使用了这个小函数:

  def calculate_size(format)
    # Only for numeric formats, String formats will raise a TypeError
    elements = 0
    format.each_char do |c|
      if c =~ /\d/
        elements += c.to_i - 1
      else
        elements += 1
      end
    end
    ([ 0 ] * elements).pack(format).length
  end

这构造了一个由正确数量的零组成的数组,调用 pack( )与您的格式,并返回长度(以字节为单位)。零在这种情况下起作用,因为它们可以转换为每种数字格式(整数、双精度、浮点数等)。

I haven't found a built-in way to do this, but I've had success with this small function when I know I'm dealing with only numeric formats:

  def calculate_size(format)
    # Only for numeric formats, String formats will raise a TypeError
    elements = 0
    format.each_char do |c|
      if c =~ /\d/
        elements += c.to_i - 1
      else
        elements += 1
      end
    end
    ([ 0 ] * elements).pack(format).length
  end

This constructs an array of the proper number of zeros, calls pack() with your format, and returns the length (in bytes). Zeros work in this case because they're convertible to each of the numeric formats (integer, double, float, etc).

时光瘦了 2024-10-15 19:56:10

我不知道有什么捷径,但你可以打包一个并询问它有多长:

length_of_five_packed_doubles = 5 * [1.0].pack('d').length

顺便说一下,一个 ruby​​ 数组与 pack 方法似乎在功能上等同于 python 的 struct 模块。 Ruby 几乎复制了 perl 的 pack 并将它们作为方法放在 Array 类上。

I don't know of a shortcut but you can just pack one and ask how long it is:

length_of_five_packed_doubles = 5 * [1.0].pack('d').length

By the way, a ruby array combined with the pack method appears to be functionally equivalent to python's struct module. Ruby pretty much copied perl's pack and put them as methods on the Array class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文