如何在Ruby中将整数转换为字节字符串



在Python中,您可以将整数转换为32字节的大端序,如下所示:

num.to_bytes(32, 'big')
# example
>>> (100).to_bytes(32, 'big')
b'x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00d'

https://docs.python.org/3/library/stdtypes.html#int.to_bytes

我如何在Ruby中实现这一点?

def to_bytestring( num_chars=nil )
unless num_chars
bits_needed = Math.log( self ) / Math::LOG2
num_chars = ( bits_needed / 8.0 ).ceil
end
if pack_code = { 1=>‘C’, 2=>‘S’, 4=>‘L’ }[ num_chars ]
[ self ].pack( pack_code )
else
(0…(num_chars)).map{ |i|
(( self >> i*8 ) & 0xFF ).chr
}.join
end
end

您也可以查看此链接https://www.ruby-forum.com/t/integer-to-byte-string-speed-improvements/67110

相关内容

  • 没有找到相关文章

最新更新