Распечатайте интервал в двоичном представлении с помощью C

А вот и последняя запись4: немного очистил ваш код, это должно помочь вам начать. https://codepen.io/anon/pen/xmeWBO?editors=1100

.container{
    margin-left:20px;
    display:flex;
    flex-direction: row;
}
.logo{
    width: auto;
    fill:orange;
    height: 57px;
}

a {
  text-decoration: none;
  color: inherit;
}

ul {
  list-style: none;
  display: flex;
  flex-grow: 1;

}

ul li {
  padding: 1rem
}

.svg-container {
  display: flex;
}

.svg-container svg {
  height: 20px;
    padding: 1.8rem 1rem;
}

23
задан Yu Hao 20 August 2013 в 04:43
поделиться

8 ответов

Here's another option that is more optimized where you pass in your allocated buffer. Make sure it's the correct size.

// buffer must have length >= sizeof(int) + 1
// Write to the buffer backwards so that the binary representation
// is in the correct order i.e.  the LSB is on the far right
// instead of the far left of the printed string
char *int2bin(int a, char *buffer, int buf_size) {
    buffer += (buf_size - 1);

    for (int i = 31; i >= 0; i--) {
        *buffer-- = (a & 1) + '0';

        a >>= 1;
    }

    return buffer;
}

#define BUF_SIZE 33

int main() {
    char buffer[BUF_SIZE];
    buffer[BUF_SIZE - 1] = '\0';

    int2bin(0xFF000000, buffer, BUF_SIZE - 1);

    printf("a = %s", buffer);
}
31
ответ дан 29 November 2019 в 01:41
поделиться

Пара вещей:

int f = 32;
int i = 1;
do{
  str[--f] = i^a?'1':'0';
}while(i<<1);
  • Это сильно зависит от платформы, но, возможно, эта идея поможет вам начать.
  • Почему бы не использовать memset (str, 0, 33) для установки всего массива char в 0?
  • Не забудьте free () !!! массив char * после вызова вашей функции!
0
ответ дан 29 November 2019 в 01:41
поделиться
#include<stdio.h>
//#include<conio.h>  // use this if you are running your code in visual c++,      linux don't 
                     // have this library. i have used it for getch() to hold the screen for input char.

void showbits(int);
int main()
{
    int no;
    printf("\nEnter number to convert in binary\n");
    scanf("%d",&no);
    showbits(no);
//  getch();        // used to hold screen... 
                    // keep code as it is if using gcc. if using windows uncomment #include & getch()
    return 0;   

}
void showbits(int n)
{
    int i,k,andmask;

    for(i=15;i>=0;i--)
    {
        andmask = 1 << i;
        k = n & andmask;

        k == 0 ? printf("0") : printf("1");
    }

}
1
ответ дан 29 November 2019 в 01:41
поделиться

Вот простой алгоритм.

void decimalToBinary (int num) {

        //Initialize mask
        unsigned int mask = 0x80000000;
        size_t bits = sizeof(num) * CHAR_BIT;

        for (int count = 0 ;count < bits; count++) {

            //print
            (mask & num ) ? cout <<"1" : cout <<"0";

            //shift one to the right
            mask = mask >> 1;
        }
    }
1
ответ дан 29 November 2019 в 01:41
поделиться

Несколько предложений:

  • завершить нулем вашу строку
  • не использовать магические числа
  • проверить возвращаемое значение malloc()
  • не приводят возвращаемое значение malloc()
  • используют двоичные операции вместо арифметических, так как вы заинтересованы в двоичном представлении
  • нет нужно дважды зацикливаться

Вот код:

#include <stdlib.h>
#include <limits.h>

char * int2bin(int i)
{
    size_t bits = sizeof(int) * CHAR_BIT;

    char * str = malloc(bits + 1);
    if(!str) return NULL;
    str[bits] = 0;

    // type punning because signed shift is implementation-defined
    unsigned u = *(unsigned *)&i;
    for(; bits--; u >>= 1)
        str[bits] = u & 1 ? '1' : '0';

    return str;
}
8
ответ дан 29 November 2019 в 01:41
поделиться

Две вещи:

  1. Куда вы помещаете символ NUL? Я не вижу места, где установлено '\ 0' .
  2. Int подписан, и 0xFF000000 будет интерпретироваться как отрицательное значение. Так что while (a> 0) сразу будет ложным.

В сторону: внутренняя функция malloc уродлива. А как насчет предоставления буфера для int2bin?

0
ответ дан 29 November 2019 в 01:41
поделиться

Your string isn't null-terminated. Make sure you add a '\0' character at the end of the string; or, you could allocate it with calloc instead of malloc, which will zero the memory that is returned to you.

By the way, there are other problems with this code:

  • As used, it allocates memory when you call it, leaving the caller responsible for free()ing the allocated string. You'll leak memory if you just call it in a printf call.
  • It makes two passes over the number, which is unnecessary. You can do everything in one loop.

Here's an alternative implementation you could use.

#include <stdlib.h>
#include <limits.h>

char *int2bin(unsigned n, char *buf)
{
    #define BITS (sizeof(n) * CHAR_BIT)

    static char static_buf[BITS + 1];
    int i;

    if (buf == NULL)
        buf = static_buf;

    for (i = BITS - 1; i >= 0; --i) {
        buf[i] = (n & 1) ? '1' : '0';
        n >>= 1;
    }

    buf[BITS] = '\0';
    return buf;

    #undef BITS
}

Usage:

printf("%s\n", int2bin(0xFF00000000, NULL));

The second parameter is a pointer to a buffer you want to store the result string in. If you don't have a buffer you can pass NULL and int2bin will write to a static buffer and return that to you. The advantage of this over the original implementation is that the caller doesn't have to worry about free()ing the string that gets returned.

A downside is that there's only one static buffer so subsequent calls will overwrite the results from previous calls. You couldn't save the results from multiple calls for later use. Also, it is not threadsafe, meaning if you call the function this way from different threads they could clobber each other's strings. If that's a possibility you'll need to pass in your own buffer instead of passing NULL, like so:

char str[33];
int2bin(0xDEADBEEF, str);
puts(str);
7
ответ дан 29 November 2019 в 01:41
поделиться

Two simple versions coded here (reproduced with mild reformatting).

#include <stdio.h>

/* Print n as a binary number */
void printbitssimple(int n) 
{
    unsigned int i;
    i = 1<<(sizeof(n) * 8 - 1);

    while (i > 0) 
    {
        if (n & i)
            printf("1");
        else
            printf("0");
        i >>= 1;
    }
}

/* Print n as a binary number */
void printbits(int n) 
{
    unsigned int i, step;

    if (0 == n)  /* For simplicity's sake, I treat 0 as a special case*/
    {
        printf("0000");
        return;
    }

    i = 1<<(sizeof(n) * 8 - 1);

    step = -1; /* Only print the relevant digits */
    step >>= 4; /* In groups of 4 */
    while (step >= n) 
    {
        i >>= 4;
        step >>= 4;
    }

    /* At this point, i is the smallest power of two larger or equal to n */
    while (i > 0) 
    {
        if (n & i)
            printf("1");
        else
            printf("0");
        i >>= 1;
    }
}

int main(int argc, char *argv[]) 
{
    int i;
    for (i = 0; i < 32; ++i) 
    {
        printf("%d = ", i);
        //printbitssimple(i);
        printbits(i);
        printf("\n");
    }

    return 0;
}
0
ответ дан 29 November 2019 в 01:41
поделиться
Другие вопросы по тегам:

Похожие вопросы: