First, you should avoid global variables and prefer to use local variables. In almost no language use global variable is good programming practice and it is very easy to make up a code tightly tied, confused, bugged and difficult to move when using global variables. So always avoid them.
Second, I think returning as a string is best. Use ..
to concatenate strings.
Third, the operator of the rest of the division is the %
.
Fourth, use the function mat.corte
to remove the fractions. The reason is that you want the split by two at each step to be an entire split.
Fifth, the loop must rotate until the number becomes zero.
Sixth, I put two se
to deal with zero and negative numbers.
Here’s 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 produced are expected, so it is possible to believe that my implementation is correct.
Ah, and this is the first time I’ve had contact with that language. Before I saw your question, I didn’t even know it existed.
For those who do not know what prism is: http://linguagemprisma.br4.biz
– Victor Stafusa
This comment was not for you. It was for other people who come to see your question and do not understand what it is.
– Victor Stafusa
Well, I edited the question and voted to reopen it. If you put in it the code that you’ve already tried to do, it helps convince other users to reopen it.
– Victor Stafusa
What I asked was how to convert integer to binary and not hexadecimal. Now if the function does something else, dot to it.
– Rafael Lemos
Do you want to return a table? Returning a string with zeros and ones would not be better?
– Victor Stafusa
I put a table because it came to my head, but it can be a chain too, for me whatever.
– Rafael Lemos