Discord
Community
DARK THEME

# hex binary to binary cut

I have a hex number like D4 which is equal 11010100 in binary. I need to get the value of the first bit in a bool variable and the 7 other into a number (so for the exemple of D4; The bool would be true and the number variable would be 84)

For this you should use Python, it comes with a bunch of functions such as `bin`, `int` and `hex`, which are extremely helpful for such things.

What I was able to pull out, was something along the lines of this (I made it a bit more human readable :P):

``````num = "D4"
int_num = int(num,16)
bin_num = bin(int_num)[2:]
``````

`int_num` is the hexadecimal number converted back into an integer, and `bin_num` is the number convered into binary, but without the `0b` at the beginning.

And here comes one of pythons sneaky little advantages in.

With `bin_num[0]` you can get a letter from the string like it's an array (string, the array in disguise ;P).

So

``````first_bit = bool(bin_num[0])
binary_data = bin_num[1:]
final_num = int(binary_data,2)
``````

will result in the variable `first_bit`, which is the first bit of the binary number as a boolean, and `final_num`, which the number as integer but without the first bit.

here's how to do it in javascript

``````// javascript

convertTo = function(n, c){
return (n.toString(c))
}

global.convertTo = convertTo;
``````

main file

``````init = function()
num = 0xD4
bin_str = convertTo(num,2)
print("bin_str: " + bin_str )
end
``````