Incorrect reading of row symbols
-
Main objective: Write a function that translates a positive whole of the decimal place into a binary form, using logical operations, and returns the result as a line.
The following error is made: 0xcccccc RO error in reading the row symbols:
#include <stdlib.h> #include <fstream> #include <cstdio> #include <string.h> #include <stdio.h> #include <cstdlib> #include <cstring> using namespace std;
char *f(unsigned int a) {
int size = sizeof(int) * 8; // количество бит в числе
char *str = new char[size + 1]; // память под строку по количеству бит
unsigned int p = 1; // переменная для проверки разрядовfor (int i = 0; i < size; i++) { if (a & p) str[i] = 1; else str[i] = 0; // проверка разряда p = p << 1; // сдвиг единицы влево для проверки следующего разряда } for (int i = size - 1; i >= 0; i--) if (str[i] == 1) { //пропускаем нули до места, когда впервые появляется 1 str[i + 1] = '\0'; break; } for (int i = 0; i <= size / 2; i++) { char t = str[i]; str[i] = str[size - i - 1]; str[size - i - 1] = str[i]; } return str;
}
int main() {
int n = 2; cout << n << endl; char *s = f(n); //вызываем функцию и получаем двоичную запись числа cout << s; delete[]s; //освобождаем память
}
There's a mistake in these places.
char *s = f(n);
char *str = new char[size + 1];
-
No mistake. the truth and the code doesn't work:
I take it you want the number to be seen in two and put it in line?
You have a mistake here:
if (a & p) str[i] = 1;
Why are you writing?
1
Not'1'
?And then the mistakes, the program doesn't work, the empty line.
The idea is that your code should be:
char* f(unsigned int a) { const int size = sizeof(int) * 8; // количество бит в числе char* str = new char[size + 1]; // память под строку по количеству бит
bool isFirst = false; int pos = 0; for (int i = size - 1; i >= 0; i--) { if ((a & (unsigned int)(1 << i)) && !isFirst) isFirst = true; if (isFirst) { str[pos] = (a & (unsigned int)(1 << i)) ? '1' : '0'; pos += isFirst ? 1 : 0; } } str[pos] = '\0'; return str;
}