hex = {'a' => 10, 'b' => 11, 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15}
value = '62ee6190'
numbers = value.split('')
@total, @c = 0, ((value.length)-1)
numbers.each do |n|
if n =~ /[[:alpha:]]/
n = hex[n]
else
n = n.to_i
end
puts "#{n} * 16 ** #{@c} = #{n * 16 ** @c}"
@total += (n * 16 ** @c)
@c -= 1
end
puts @total
-Ninjex- wrote:Let's take an example Hexadecimal number: 8A4C
...
Last thing to do is add the values
32768+2560+64+12 = 35404
Randoph wrote:One question tho, why do you count the numbers from right to left? Wouldn't it be more logical that the 8 is in the 1st(0th) posistion? That way you get:
8*16^0 = 8
10*16^1 = 160
4*16^2 = 1024
12*16^3 = 49152
8+160+1024+49152 = 50344
-Ninjex- wrote:Randoph wrote:One question tho, why do you count the numbers from right to left? Wouldn't it be more logical that the 8 is in the 1st(0th) posistion? That way you get:
8*16^0 = 8
10*16^1 = 160
4*16^2 = 1024
12*16^3 = 49152
8+160+1024+49152 = 50344
Well, 8 is the first digit, but it has the highest power.
Just like the decimal value '110' break it down
1 * 10 ** 2 = 100
1 * 10 ** 1 = 10
0 * 10 ** 0 = 0
Answer 110
100 has a power of 2 (two places away from the first digit)
10 has a power of 1 (one place away from the first digit)
0 has a power of 0 (it's the first digit)
Looking at this wiki, may help you:
http://en.wikipedia.org/wiki/Power_of_10
So for hexadecimal, we just substitute the 10 with 16
If you do it in reverse, you will be telling it that 100 has a power of 0, 10 has a power of 1, and 0 has a power of 2, which is false, and will lead to an incorrect result as you can see from your above example.
tripbeam wrote:Thank you guys! i finnaly understand it, took me ages
Users browsing this forum: No registered users and 0 guests