Prism - How to convert integer to binary?

1

I need a function in the Prism language that converts an integer to its binary form. For example, to convert 255 to 11111111 .

I have to create a formula such as link

tab = {}                           // declarando uma tabela vazia
funcao bits(n)                     // "n" é o número inteiro
    enquanto verdadeiro inicio     // laço para preencher a tabela
    n = n / 2                      // divido n por 2 até chegar a 0
    resto = "resto de n por 2"     // tenho que pegar o resto da divisão
    tabela.insira(tab,1,resto)     // alimentando a tabela
    fim                            // fim do laço
    retorne tab                    // retorna a tabela com os binários
fim

imprima(bits(255))                 //--------- saída >> 11111111
    
asked by anonymous 09.10.2017 / 02:54

1 answer

2

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.

    
09.10.2017 / 14:04