Convert INT to Binary String

Godot Version



Hi Everyone, is there a simple way to convert an INT to a Binary String representation.

I’ve written a simple routine to do it but I would prefer something like:

var BinStr : String = intValue.to_Binary()



str(bool(number)) str() bool()

I totally misunderstood the question.

I’m sorry but you’ve lost me,

How does that return me an 8 digit string with the binary representation of the number???

I use the following at the moment:

func to_binary(intValue: int) -> String:
	var bin_str: String = ""
	while intValue > 0:
		bin_str = str(intValue & 1) + bin_str
		intValue = intValue >> 1
	return bin_str


Sorry, I totally misunderstood the question :sweat:

I’m not aware of a simpler way to do that than the one you posted.

edit: don’t do this, see below about num_int64(), much better

Hi I was looking for a way to do same, found the 0b literal specifier which does a great job the other direction but sadly there is no format specifier for binary that I can find. So I made this, I guess it’ll do for now. Pretty sure I got the nibbles right but do double check to be sure.

var _nbls = [	"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", \
		null, null, null, null, null, null, null,  \
		"1010", "1011", "1100", "1101", "1110", "1111" ]
var _asc = ("%04X" % _myInt).to_ascii_buffer();
var _ostr = _nbls[_asc[0]-48] + _nbls[_asc[1]-48] + _nbls[_asc[2]-48] + _nbls[_asc[3]-48];
print (_ostr, " -> ", str(_myInt));

… “0001101010111011 → 7935”

You use this method num_int64 with base 2

1 Like

Perfect, thanks.