O
O
Oleg Seledets2019-04-27 21:48:18
Qt
Oleg Seledets, 2019-04-27 21:48:18

Why does the translation from 2 to 10 and vice versa not work?

There are two functions for converting to 10 and 2 system

spoiler
int BinDec(char* bin, int size)
{
    int rez(0), i;
    for(i = size - 1; i >= 0; --i)
        rez += (bin[i] - 48)<<i;
    return rez;
}
char* DecBin(int chislo, int size)
{
    int i;
    char* bin = new char[size];
    for(i = size - 1; i >= 0; --i)
    {
        if(!((i + 1) % 8)){}
        bin[i] = ((chislo>>i)&1) + 48;
    }
    return bin;
}

The output goes like this:
spoiler
const char* ch = DecBin(ui->vih1->text().toInt(),8);
        ui->vhod1->setText(QString::fromLocal8Bit(ch));

Incorrect data output occurs:
input: 10 output: 01010000"""""""""""""""ooooooooo
input: 173 output: 10110101"""""""""""""""" ooooooooooo

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly, 2019-04-27
@oleja1ee7

Use the standard functions as long as you have Qt. QString is able both in number and from number, with indication of number system. See the toInt and number methods.

R
res2001, 2019-04-28
@res2001

There are 2 errors in DecBin():
1. You fill the string from the end, but you need to from the beginning. Pay attention to conclusion 173 (if you do not take into account the garbage tail, about which in paragraph 2) - the answer is correct, only written the other way around.
2.After the conversion, you need to add a trailing 0, because the output is a C string. Accordingly, memory must be allocated 1 byte more than necessary. Due to the lack of a terminating null, the output does not end at the end of your buffer, but continues to output the contents of the memory after the buffer until it encounters a null byte, hence the garbage at the end.
It is also possible not to add a null byte, but in this case it is not necessary to treat the pointer returned by DecBin() as a string, but to work with it as an array of bytes. Those. output a strictly specified number of bytes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question