Created
May 25, 2024 04:07
-
-
Save ParadoxV5/51deba47855cd758dfdda0d32709dce9 to your computer and use it in GitHub Desktop.
Pack an integer to a byte-sequence string. Discussed in https://discord.com/invite/ruby-518658712081268738 #general. I dedicate this to the Public Domain.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def int2bytestr(int, bytesize = int.size) | |
[ | |
# Format to hex, left-pad with `0` (big-endian) for `bytesize * 2` nibbles | |
sprintf('%0*X', bytesize * 2, int) | |
].pack 'H*' # Pack string of hex chars to string of raw bytes | |
end | |
# Demo | |
print "actual\t" | |
p int2bytestr(0x4_20_69_de_ad_be_ef_13_37, 10) | |
print "expect\t" | |
p %w[0 4 20 69 de ad be ef 13 37].map { _1.hex.chr }.join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment