Answer the question
In order to leave comments, you need to log in
Why does the translation from 2 to 10 and vice versa not work?
There are two functions for converting to 10 and 2 system
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;
}
const char* ch = DecBin(ui->vih1->text().toInt(),8);
ui->vhod1->setText(QString::fromLocal8Bit(ch));
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question