First, you'd better avoid global variables and prefer to use local variables. In almost no language using global variable is good programming practice and it is very easy to make a well-typed, confused, buggy, and hard-to-move code when using global variables. So always avoid them.
Second, I think returning as string is better. Use ..
to concatenate strings.
Third, the remainder operator of the division is %
.
Fourth, use the mat.corte
function to remove fractions. The reason is that you want the division by two at each step to be an entire division.
Fifth, the loop must rotate until the number becomes zero.
Sixth, I put two se
to deal with zero and negative numbers.
Here is the code:
// "n" é o número inteiro.
funcao bits(n)
// Lida com o caso especial de n ser zero.
se n == 0 entao
retorne "0"
fim
// Declara uma string inicialmente vazia.
local resposta = ""
// Verifica se é negatiovo para colocar o sinal de menos depois.
local menos = falso
se n < 0 entao
menos = verdadeiro
n = -n
fim
// Laço para preencher a string.
enquanto n > 0 inicio
// Pega o resto da divisão.
local resto = n % 2
// Isola os demais dígitos do número.
n = mat.corte(n / 2)
// Alimenta a string.
resposta = resto .. resposta
fim
// Coloca o sinal de menos de volta, se necessário.
se menos entao
resposta = "-" .. resposta
fim
// Retorna a string com os binários.
retorne resposta
fim
imprima(bits(255))
imprima(bits(-5))
imprima(bits(5))
imprima(bits(48973568))
imprima(bits(0))
imprima(bits(1))
imprima(bits(-1))
imprima(bits(2))
Note these instructions imprima
at the end. They are there to test the program. Here is the output produced:
11111111
-101
101
10111010110100011100000000
0
1
-1
10
Note that these binary numbers are produced as expected, so it's possible to believe that my implementation is correct.
Oh, and this is the first time I had contact with this language. Before I saw your question, I did not even know it existed.