Wyświetla binarną reprezentację liczby w C? [duplikat]
Możliwy duplikat:
czy istnieje konwerter printf do drukowania w formacie binarnym?
Wciąż uczę się C i zastanawiałem się:
Biorąc pod uwagę liczbę, czy można zrobić coś takiego jak poniżej?
char a = 5;
printf("binary representation of a = %b",a);
> 101
Czy musiałbym napisać własną metodę, aby wykonać transformację na binarną?
8 answers
Tak (napisz własną), coś w rodzaju poniższej pełnej funkcji.
#include <stdio.h> /* only needed for the printf() in main(). */
#include <string.h>
/* Create a string of binary digits based on the input value.
Input:
val: value to convert.
buff: buffer to write to must be >= sz+1 chars.
sz: size of buffer.
Returns address of string or NULL if not enough space provided.
*/
static char *binrep (unsigned int val, char *buff, int sz) {
char *pbuff = buff;
/* Must be able to store one character at least. */
if (sz < 1) return NULL;
/* Special case for zero to ensure some output. */
if (val == 0) {
*pbuff++ = '0';
*pbuff = '\0';
return buff;
}
/* Work from the end of the buffer back. */
pbuff += sz;
*pbuff-- = '\0';
/* For each bit (going backwards) store character. */
while (val != 0) {
if (sz-- == 0) return NULL;
*pbuff-- = ((val & 1) == 1) ? '1' : '0';
/* Get next bit. */
val >>= 1;
}
return pbuff+1;
}
Dodaj ten główny na końcu, aby zobaczyć go w działaniu:
#define SZ 32
int main(int argc, char *argv[]) {
int i;
int n;
char buff[SZ+1];
/* Process all arguments, outputting their binary. */
for (i = 1; i < argc; i++) {
n = atoi (argv[i]);
printf("[%3d] %9d -> %s (from '%s')\n", i, n,
binrep(n,buff,SZ), argv[i]);
}
return 0;
}
Uruchom go z "progname 0 7 12 52 123"
aby uzyskać:
[ 1] 0 -> 0 (from '0')
[ 2] 7 -> 111 (from '7')
[ 3] 12 -> 1100 (from '12')
[ 4] 52 -> 110100 (from '52')
[ 5] 123 -> 1111011 (from '123')
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-04-01 04:40:47
Nie ma bezpośredniego sposobu (tj. użycia printf
lub innej standardowej funkcji bibliotecznej), aby ją wydrukować. Będziesz musiał napisać własną funkcję.
/* This code has an obvious bug and another non-obvious one :) */
void printbits(unsigned char v) {
for (; v; v >>= 1) putchar('0' + (v & 1));
}
Jeśli używasz terminala, możesz użyć kodów sterujących do drukowania bajtów w naturalnej kolejności:
void printbits(unsigned char v) {
printf("%*s", (int)ceil(log2(v)) + 1, "");
for (; v; v >>= 1) printf("\x1b[2D%c",'0' + (v & 1));
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-10 22:04:00
Na podstawie dirkgently ' s answer , ale naprawia dwa błędy i zawsze drukuje stałą liczbę cyfr:
void printbits(unsigned char v) {
int i; // for C89 compatability
for(i = 7; i >= 0; i--) putchar('0' + ((v >> i) & 1));
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:40
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
void displayBinary(int n)
{
char bistr[1000];
itoa(n,bistr,2); //2 means binary u can convert n upto base 36
printf("%s",bistr);
}
int main()
{
int n;
cin>>n;
displayBinary(n);
getch();
return 0;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-10 17:11:37
Użyj tabeli wyszukiwania, Jak:
char *table[16] = {"0000", "0001", .... "1111"};
Następnie wydrukuj każdy skubek w ten sposób
printf("%s%s", table[a / 0x10], table[a % 0x10]);
Z pewnością możesz użyć tylko jednego stołu, ale będzie on nieznacznie szybszy i zbyt duży.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-16 19:36:09
Ten kod powinien obsłużyć twoje potrzeby do 64 bitów.
char* pBinFill(long int x,char *so, char fillChar); // version with fill
char* pBin(long int x, char *so); // version without fill
#define width 64
char* pBin(long int x,char *so)
{
char s[width+1];
int i=width;
s[i--]=0x00; // terminate string
do
{ // fill in array from right to left
s[i--]=(x & 1) ? '1':'0'; // determine bit
x>>=1; // shift right 1 bit
} while( x > 0);
i++; // point to last valid character
sprintf(so,"%s",s+i); // stick it in the temp string string
return so;
}
char* pBinFill(long int x,char *so, char fillChar)
{ // fill in array from right to left
char s[width+1];
int i=width;
s[i--]=0x00; // terminate string
do
{
s[i--]=(x & 1) ? '1':'0';
x>>=1; // shift right 1 bit
} while( x > 0);
while(i>=0) s[i--]=fillChar; // fill with fillChar
sprintf(so,"%s",s);
return so;
}
void test()
{
char so[width+1]; // working buffer for pBin
long int val=1;
do
{
printf("%ld =\t\t%#lx =\t\t0b%s\n",val,val,pBinFill(val,so,0));
val*=11; // generate test data
} while (val < 100000000);
}
Output:
00000001 = 0x000001 = 0b00000000000000000000000000000001
00000011 = 0x00000b = 0b00000000000000000000000000001011
00000121 = 0x000079 = 0b00000000000000000000000001111001
00001331 = 0x000533 = 0b00000000000000000000010100110011
00014641 = 0x003931 = 0b00000000000000000011100100110001
00161051 = 0x02751b = 0b00000000000000100111010100011011
01771561 = 0x1b0829 = 0b00000000000110110000100000101001
19487171 = 0x12959c3 = 0b00000001001010010101100111000011
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-04-01 07:31:24
Musisz napisać własną transformację. Tylko liczby dziesiętne, szesnastkowe i ósemkowe są obsługiwane przez SPECYFIKATORY FORMATU.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-31 04:20:34
W języku C nie ma bezpośredniego określenia formatu. Chociaż napisałem ten szybki fragment Pythona, aby pomóc ci zrozumieć proces krok po kroku, aby rzucić własne.
#!/usr/bin/python
dec = input("Enter a decimal number to convert: ")
base = 2
solution = ""
while dec >= base:
solution = str(dec%base) + solution
dec = dec/base
if dec > 0:
solution = str(dec) + solution
print solution
Explained:
Dec = input ("Enter a decimal number to convert:") - pyta użytkownika o wejście numeryczne (istnieje wiele sposobów, aby to zrobić w C przez scanf na przykład)
Base = 2 - podaj naszą Bazę to 2 (binary)
Solution = "" - Utwórz pusty łańcuch, w którym połączymy nasze rozwiązanie
While dec > = base: - while nasza liczba jest większa od wprowadzonej Bazy
Solution = str ( dec % base) + solution - pobieramy moduł liczby do bazy i dodajemy ją do początku naszego łańcucha (musimy dodać liczby od prawej do lewej używając metody division I rest). funkcja str () zamienia wynik operacji na łańcuch znaków. Nie można łączyć liczb całkowitych z łańcuchami w Pythonie bez konwersji typu.
Dec = Dec / base - podziel liczbę dziesiętną przez bazę w preperacji, aby wziąć następny modulo
If dec > 0: solution = str (dec) + solution - jeśli cokolwiek zostanie, dodaj go do początku (będzie to 1, jeśli już)
Print solution - wypisuje ostateczną liczbę
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-31 04:43:55