Coding Challenge #4 - Bit Manipulation
-
FUZE coding challenge #4
Hi everyone! Welcome to challenge #4 of the coding challenge series.
The rules are:-
Post your Fuze code below. (If the code is too long to type you can post the ID of the project instead).
-
There will be 2 tasks per challenge, a Beginners challenge and an Advanced challenge. Anyone can participate in one or both tasks.
-
We are always open to suggestions!
-
Have fun coding!!
TASK #1
LEVEL: Beginner
Take an integer and reverse its bits within a range of 1 byte or 0 - 255.
You are not allowed to use any Fuze functions (Your own defined functions are allowed).
you can choose to do this iteratively or recursively and print the result.
The result must be a string showing the integer before the reversing and after.Example:
"The number '112' in binary is: 01110000, reversed would be: '14' - 00001110"TASK #2
LEVEL: Advanced
In this task you must take two integers, multiply them and then print the result.
You are not allowed to use the multiply operator (*).
You can only use addition (+) and bitwise operations (&, |, ~, <<, >>).
The output must be a string displaying the result and the number of loops it took to complete the given task.Example:
"5 x 5 = 25 in (X amount of loops)" -
-
These are my efforts.
-
Hi guys! Since it's getting close to the next challenge. I thought I'd post up my solution for last month's challenge.
table = [1, 2, 4, 8, 16, 32, 64, 128] rtable = [128, 64, 32, 16, 8, 4, 2, 1] //TASK #1 task1_n = random(255) function _abs(x) r = 0 if x < 0 then r = (~x) + 1 else r = x endif return r function extract_bin(n) r = "00000000" for i = 0 to 8 loop if n & rtable[i] then r[i] = "1" else r[i] = "0" endif repeat return r function reverse_bin(n) r = 0 for i = 0 to 8 loop if n & table[i] then r = r | rtable[i] endif repeat return r print(str(task1_n) + " " + extract_bin(task1_n) + " -> " + str(reverse_bin(task1_n)) + " " + extract_bin(reverse_bin(task1_n))) //TASK #2 task2_n1 = random(255) task2_n2 = random(255) is_negative1 = random(2) is_negative2 = random(2) function mul(a, b) r = 0 sign = 0 loops = 0 if a == 0 or b == 0 then r = 0 else if a == 1 then r = b else if a == -1 then r = -b else if b == 1 then r = a else if b == -1 then r = -a else if a < 0 or b < 0 then sign = 1 endif if a < 0 and b < 0 then sign = 0 endif a = _abs(a) b = _abs(b) for i = 0 to 8 loop if b & table[i] then r += a endif a = a << 1 loops += 1 repeat endif endif endif endif endif if sign then r = -r endif res = [r, loops] return res if is_negative1 then task2_n1 = -task2_n1 endif if is_negative2 then task2_n2 = -task2_n2 endif task2_res = mul(task2_n1, task2_n2) print(str(task2_n1) + " x " + str(task2_n2) + " = " + str(task2_res[0]) + " in " + str(task2_res[1]))