Created
October 21, 2010 16:28
-
-
Save dentarg/638812 to your computer and use it in GitHub Desktop.
Some functions to convert binary to hex and vice versa
This file contains hidden or 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
| #!/usr/local/bin/ruby | |
| # bin functions | |
| def bin2dec(str) | |
| return eval("0b#{str}.to_i") | |
| end | |
| def bin2hex(str) | |
| return "todo" | |
| end | |
| # dec functions | |
| def dec2bin(str) | |
| dec = str.to_i | |
| array = Array.new(8) | |
| array = Array.new(16) if dec>255 | |
| for i in 1..array.size | |
| array[i] = dec % 2 | |
| dec = dec/2 | |
| end | |
| return array.reverse.to_s | |
| end | |
| def dec2hex(str) | |
| return "todo" | |
| end | |
| # hex functions | |
| def hex2bin(str) | |
| return dec2bin(hex2dec(str)) | |
| end | |
| def hex2dec(str) | |
| return str.hex | |
| end | |
| # print function | |
| def my_print(bin, dec, hex) | |
| puts "#{bin}\t#{dec}\t#{hex}" | |
| end | |
| # num functions | |
| def bin(str) | |
| bin = dec2bin(bin2dec(str)) | |
| dec = bin2dec(str) | |
| hex = bin2hex(str) | |
| my_print(bin, dec, hex) | |
| end | |
| def dec(str) | |
| bin = dec2bin(str) | |
| dec = str | |
| hex = dec2hex(str) | |
| my_print(bin, dec, hex) | |
| end | |
| def hex(str) | |
| bin = hex2bin(str) | |
| dec = hex2dec(str) | |
| hex = str | |
| my_print(bin, dec, hex) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment