Home > Enterprise >  convert decimal to hexidecimal 2 digits at a time Ruby
convert decimal to hexidecimal 2 digits at a time Ruby

Time:12-09

I am trying to convert a string of decimal values to hex, grabbing two digits at a time

so for example, if i were to convert these decimals two digits at a time

01 67 15 06 01 76 61 73

this would be my result

01430F06014C3D49

i know that str.to_s(16) will convert decimal to hex but like i said I need this done two digits at a time so the output is correct, and i have no clue how to do this in Ruby

here is what i have tried

str.upcase.chars.each_slice(2).to_s.(16).join

CodePudding user response:

You can use String#gsub with a regular expression and Kernel#sprintf:

"01 67 15 06 01 76 61   73".gsub(/\d{2} */) { |s| sprintf("x", s.to_i) } 
  #=> "01430f06014c3d49"

The regular expression /\d{2} */) matches two digits followed by zero or more spaces (note 73 is not followed by space).

The result of the block calculation replaces the two or three characters that were matched by the regular expression.

sprintf's formatting directive forms a sting containing 2 characters, padded to the left with '0''s, if necessary, and converting the string representation of an integer in base 10 to the string representation of an integer in base 16 ('x').

Alternatively, one could use String#% (with sprintf's formatting directives):

"01 67 15 06 01 76 61   73".gsub(/\d{2} */) { |s| "x" % s.to_i } 
  #=> "01430f06014c3d49"
  • Related