Is there any way to print number as bit32?

Hello, guys. I found that numbers in lua can be writen in format
local num = 0bXXXX_XXXX_...
But when tring to print it, it still prints regular number:
local num = 0b1111_1111 print(num) --result is 255
Is there any way to print it like
1111_1111?

I couldn’t find a built-in way, so I wrote this one real quick.

--- formats a number to display as a binary representation
--- parameters:
--- number (number): the number to format as binary
--- separator (optional, bool): whether to place underscores on 4-bit boundaries
--- length (optional, number): desired length of the formatted string, not including underscores.
---     this only adds padding, it will not shorten longer sequences.
local function format_binary(number, separator, length)
	local total = math.max(32-bit32.countlz(number), math.min(length or 0, 32))
	local result = ""
	for i = 1, total do
		result = bit32.band(number, 1) .. result
		number = bit32.rshift(number, 1)
		if separator and i < total and i % 4 == 0 then
			result = "_" .. result
		end
	end
	return result
end

-- normal formatting
print(format_binary(7)) --> 111
-- with padding and underscores
print(format_binary(7, true, 8)) --> 0000_0111
-- with padding and no underscores
print(format_binary(7, false, 8)) --> 00000111
-- with padding and underscores, but the number is too big
print(format_binary(1000, true, 8)) --> 11_1110_1000
-- I could also do something with the last one where it would automatically pad to the nearest 4-bit chunk
-- if you wanted, so it would display as 0011_1110_1000. Let me know if that's something you want,
-- or you could probably add it yourself.
1 Like

Sorry, this’s a bit unrelated to main question, but when creating number variable it lua, it’s by default 32-bit? or 64-bit?

Numbers in Lua are actually neither. They’re 64-bit floats. 53 of the bits store the number, and 11 exponent bits basically specify how many zeros come before or after the number. The largest consecutive integer that can be stored is 2^53, far more than a 32 bit integer but less than a 64 bit integer. After that, you can keep increasing the number but you need to start counting by 2s, so only even numbers can be stored. Then when you run out of room, you increase the exponent again and start counting by 4. Eventually you max out at something like 10^308. It works in the other direction as well. With negative exponent bits, you can get decimal numbers like halves, quarters, eighths, etc down to 10^-308.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.