bit轉成hex和hex轉成bit
這兩個函數一個是將bit數轉成16進制還有16進制轉成bit數。
#
# Bit convert to Hex
# bitToHex(Bit Number)
# Example : BitToHex(8)
def BitToHex(bit_number)
if bit_number <= 0
puts "0x1"
else
puts "0x"+(1 < < bit_number).to_s(base=16)
end
end
#
# Hex convert to Bit
#
# bitToHex(Hex Number)
# Example : bitToHex [0x7ff]
def HexToBit(hex_number)
str = hex_number.to_i.to_s(base=2)
length = str.length
(0..length-1).each{|i| puts "#{(length-1)i}: #{str[i]}"}
puts "binary : #{str}"
end
BitToHex(8)
# result: 0x100
HexToBit(0x7ff)
# result:
# 10: 1
# 9: 1
# 8: 1
# 7: 1
# 6: 1
# 5: 1
# 4: 1
# 3: 1
# 2: 1
# 1: 1
# 0: 1
# binary : 11111111111
留言