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 &lt; size; i++) {
        if (a &amp; p) str[i] = 1;
    
        else str[i] = 0; // проверка разряда
        p = p &lt;&lt; 1; // сдвиг единицы влево для проверки следующего разряда
    }
    
    for (int i = size - 1; i &gt;= 0; i--)
        if (str[i] == 1) { //пропускаем нули до места, когда впервые появляется 1
            str[i + 1] = '\0';
            break;
    
        }
    
    for (int i = 0; i &lt;= 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 &lt;&lt; n &lt;&lt; endl;
    char *s = f(n); //вызываем функцию и получаем двоичную запись числа
    cout &lt;&lt; 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? 1Not '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 &gt;= 0; i--) {
        if ((a &amp; (unsigned int)(1 &lt;&lt; i)) &amp;&amp; !isFirst)
            isFirst = true;
    
        if (isFirst) {
            str[pos] = (a &amp; (unsigned int)(1 &lt;&lt; i)) ? '1' : '0';
    
            pos += isFirst ? 1 : 0;
        }
    }
    
    str[pos] = '\0';
    
    return str;
    

    }


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2