Thursday, 15 May 2014

ruby - How to print numbers in hex with leading zero -



ruby - How to print numbers in hex with leading zero -

is there improve method display number in hex leading 0? tried:

i.to_s(16)

but

2.to_s(16) #=> "2"

where expect "02". tried print format:

"%02x" %

which works 2, but

"%02x" % 256 #=> "100"

where want "0100". came this:

class integer def to_hex_string ("%0x" % self).size % 2 == 0 ? "%0x" % self : "%0#{("%0x" % self).size+1}x" % self end end

it works:

2.to_hex_string #=> "02" 256.to_hex_string #=> "0100"

it works class bignumber, looks unusual such easy request needs trick this. improve idea?

you making way complicated. if want print integer in hexadecimal leading zero,

class integer def to_hex_string "0#{to_s(16)}" end end 2.to_hex_string # => 02 256.to_hex_string # => 0100

ruby hex hexdump leading-zero

No comments:

Post a Comment