These are little snippets of how you can convert between binary numbers and decimal numbers using GDScriptGodot Engine Master race
Currently, as I am writing this post, there are no built-in functions for converting between them. Knowing that I am not the first in looking for this, and that I most certainly wont be the last, I decided to post the code for doing so.

Decimal to Binary

# Takes in a decimal value (int) and returns the binary value (int)
func dec2bin(var decimal_value): 
	var binary_string = "" 
	var temp 
	var count = 31 # Checking up to 32 bits 
 
	while(count >= 0): 
		temp = decimal_value >> count 
		if(temp & 1): 
			binary_string = binary_string + "1" 
		else: 
			binary_string = binary_string + "0" 
		count -= 1 

	return int(binary_string)

Binary to Decimal

# Takes in a binary value (int) and returns the decimal value (int)
func bin2dec(var binary_value): 
	var decimal_value = 0 
	var count = 0 
	var temp 
 
	while(binary_value != 0): 
		temp = binary_value % 10 
		binary_value /= 10 
		decimal_value += temp * pow(2, count) 
		count += 1 
 
	return decimal_value

If you know of simpler ways of doing this, please comment below and let me know. I always look for ways to improve my coding.


SleepProgger from IRC://freenode #godotengine suggested the following for conversion between bin/dec:

func bin2int(bin_str):
	var out = 0
	for c in bin_str:
		out = (out << 1) + int(c=="1")
	return out

func int2bin(value):
	var out = ""
	while value > 0:
		out = str(value & 1) + out
		value = value >> 1
	return out

A different approach, but by the look of it; a cleaner approach. Thank you for letting me know. 🙂

1 thought on “[GDScript] Conversion between Binary / Decimal”

  1. I found this snippet to be very useful. Currently I am making a game based off of Multi Pile NIM. The strategy for a player involves converting each pile into binary so that you can determine how much to take from a pile to make it a ‘safe’ move and win.

Leave a Reply