Friday, 15 May 2015

Ruby binary string to hexadecimal without loosing 0000 -


is a binary string to me that I need to convert a hexadecimal string. I have this code which it very nicely

  binary = '0000010000000000000000000000000000000000000000000000000000000000000000' binary.to_i (2) .to_s (16)  

This will work normally but in this situation, the first four zeros, representing the first hexadecimal space, are left out. So 040000000000000000 instead of 400000000000000 is shown

Now, I know that I can loop through manually binary string and a In time, I can convert 4 bits, but what's an easy way to get the results of '0400000000000000'?

> Should my ideal solution be (16, '0')?

You can use it:

  Binary = "00000100000000000000000000000000000000000000000000000000000000000000 "[Binary] .Pack (" B * "). Unpack ("H *") First # = & gt; "0400000000000000"  

binary.to_i (2) will turn into a number value. No number is known about the principal zero pack ("B *") 8 bit will convert each one into one byte, giving you a binary encoded string. 8 x 0 is "\ x00" , unlike a zero byte number, string preserves leading zeros. Unpack ("H *") then converts each 4 bits into its hex representation for more information array # pack and string # unpack code.


No comments:

Post a Comment