Stampa un int in rappresentazione binaria usando C
Domanda
Sto cercando una funzione che mi permetta di stampare la rappresentazione binaria di un int. Quello che ho finora è;
char *int2bin(int a)
{
char *str,*tmp;
int cnt = 31;
str = (char *) malloc(33); /*32 + 1 , because its a 32 bit bin number*/
tmp = str;
while ( cnt > -1 ){
str[cnt]= '0';
cnt --;
}
cnt = 31;
while (a > 0){
if (a%2==1){
str[cnt] = '1';
}
cnt--;
a = a/2 ;
}
return tmp;
}
Ma quando chiamo
printf("a %s",int2bin(aMask)) // aMask = 0xFF000000
Ottengo output come;
0000000000000000000000000000000000xtpYy (E un mucchio di personaggi sconosciuti.
È un difetto nella funzione o sto stampando l'indirizzo dell'array di caratteri o qualcosa del genere? Mi dispiace, non riesco proprio a vedere dove sto sbagliando.
NB Il codice proviene da qui
EDIT: FYI non sono compiti a casa, sto cercando di eseguire il debug delle routine di manipolazione delle immagini di qualcun altro in un linguaggio sconosciuto. Se tuttavia è stato etichettato come compito a casa perché è un concetto elementare, allora il fair play.
Soluzione
Ecco un'altra opzione che è più ottimizzata quando passi nel buffer allocato. Assicurati che sia della dimensione corretta.
// 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);
}
Altri suggerimenti
Alcuni suggerimenti:
- annulla la stringa
- non usare numeri magici
- controlla il valore di ritorno di
malloc()
- non trasmettere il valore di ritorno di
malloc()
- usa le operazioni binarie invece di quelle aritmetiche poiché sei interessato alla rappresentazione binaria
- non è necessario eseguire il looping due volte
Ecco il codice:
#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;
}
La tua stringa non ha una terminazione nulla. Assicurati di aggiungere un carattere '\ 0'
alla fine della stringa; oppure, puoi allocarlo con calloc
anziché malloc
, che azzererà la memoria che ti viene restituita.
A proposito, ci sono altri problemi con questo codice:
- Se utilizzato, alloca memoria quando lo chiami, lasciando il chiamante responsabile di
free ()
nella stringa allocata. Perderai memoria se la chiami semplicemente in una chiamataprintf
. - Effettua due passaggi sul numero, il che non è necessario. Puoi fare tutto in un ciclo.
Ecco un'implementazione alternativa che potresti usare.
#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
}
Utilizzo:
printf("%s\n", int2bin(0xFF00000000, NULL));
Il secondo parametro è un puntatore a un buffer in cui si desidera archiviare la stringa del risultato. Se non si dispone di un buffer, è possibile passare NULL
e int2bin
scrivere in un buffer statico
e restituirlo a te. Il vantaggio di questo rispetto all'implementazione originale è che il chiamante non deve preoccuparsi di free ()
nella stringa che viene restituita.
Un aspetto negativo è che esiste un solo buffer statico, quindi le chiamate successive sovrascriveranno i risultati delle chiamate precedenti. Non è stato possibile salvare i risultati da più chiamate per un uso successivo. Inoltre, non è thread-safe, il che significa che se chiamate la funzione in questo modo da thread diversi, potrebbero ostruire le stringhe l'una dell'altra. Se è una possibilità, dovrai passare nel tuo buffer invece di passare NULL
, in questo modo:
char str[33];
int2bin(0xDEADBEEF, str);
puts(str);
Ecco un semplice algoritmo.
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;
}
}
questo è ciò che ho fatto per visualizzare un interger come codice binario che è separato per 4 bit:
int getal = 32; /** To determain the value of a bit 2^i , intergers are 32bits long**/
int binairy[getal]; /** A interger array to put the bits in **/
int i; /** Used in the for loop **/
for(i = 0; i < 32; i++)
{
binairy[i] = (integer >> (getal - i) - 1) & 1;
}
int a , counter = 0;
for(a = 0;a<32;a++)
{
if (counter == 4)
{
counter = 0;
printf(" ");
}
printf("%i", binairy[a]);
teller++;
}
potrebbe essere un po 'grande ma lo scrivo sempre in un modo (spero) che tutti possano capire cosa sta succedendo. spero che questo abbia aiutato.
#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");
}
}
Due cose:
- Dove metti il ??personaggio NUL? Non riesco a vedere un posto in cui è impostato
'\ 0'
. - Int è firmato e 0xFF000000 sarebbe interpretato come un valore negativo. Quindi
while (a > 0)
sarà immediatamente falso.
A parte: la funzione malloc all'interno è brutta. Che dire di fornire un buffer a int2bin?
Un paio di cose:
int f = 32;
int i = 1;
do{
str[--f] = i^a?'1':'0';
}while(i<<1);
- Dipende fortemente dalla piattaforma, ma forse questa idea sopra ti fa iniziare.
- Perché non usare memset (str, 0, 33) per impostare l'intero array di caratteri su 0?
- Non dimenticare di liberare () !!! il carattere * array dopo la tua chiamata di funzione!
Due semplici versioni codificate qui (riprodotte con una leggera riformattazione).
#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;
}
// Questo è quello che ho fatto quando il nostro insegnante ci ha chiesto di farlo
int main (int argc, char *argv[]) {
int number, i, size, mask; // our input,the counter,sizeofint,out mask
size = sizeof(int);
mask = 1<<(size*8-1);
printf("Enter integer: ");
scanf("%d", &number);
printf("Integer is :\t%d 0x%X\n", number, number);
printf("Bin format :\t");
for(i=0 ; i<size*8 ;++i ) {
if ((i % 4 == 0) && (i != 0)) {
printf(" ");
}
printf("%u",number&mask ? 1 : 0);
number = number<<1;
}
printf("\n");
return (0);
}
il modo più semplice per me farlo (per una rappresentazione a 8 bit):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char *intToBinary(int z, int bit_length){
int div;
int counter = 0;
int counter_length = (int)pow(2, bit_length);
char *bin_str = calloc(bit_length, sizeof(char));
for (int i=counter_length; i > 1; i=i/2, counter++) {
div = z % i;
div = div / (i / 2);
sprintf(&bin_str[counter], "%i", div);
}
return bin_str;
}
int main(int argc, const char * argv[]) {
for (int i = 0; i < 256; i++) {
printf("%s\n", intToBinary(i, 8)); //8bit but you could do 16 bit as well
}
return 0;
}
Ecco un'altra soluzione che non richiede un carattere *.
#include <stdio.h>
#include <stdlib.h>
void print_int(int i)
{
int j = -1;
while (++j < 32)
putchar(i & (1 << j) ? '1' : '0');
putchar('\n');
}
int main(void)
{
int i = -1;
while (i < 6)
print_int(i++);
return (0);
}
O qui per maggiore leggibilità:
#define GRN "\x1B[32;1m"
#define NRM "\x1B[0m"
void print_int(int i)
{
int j = -1;
while (++j < 32)
{
if (i & (1 << j))
printf(GRN "1");
else
printf(NRM "0");
}
putchar('\n');
}
Ed ecco l'output:
11111111111111111111111111111111
00000000000000000000000000000000
10000000000000000000000000000000
01000000000000000000000000000000
11000000000000000000000000000000
00100000000000000000000000000000
10100000000000000000000000000000
#include <stdio.h>
#define BITS_SIZE 8
void
int2Bin ( int a )
{
int i = BITS_SIZE - 1;
/*
* Tests each bit and prints; starts with
* the MSB
*/
for ( i; i >= 0; i-- )
{
( a & 1 << i ) ? printf ( "1" ) : printf ( "0" );
}
return;
}
int
main ()
{
int d = 5;
printf ( "Decinal: %d\n", d );
printf ( "Binary: " );
int2Bin ( d );
printf ( "\n" );
return 0;
}
Non così elegante, ma raggiunge il tuo obiettivo ed è molto facile da capire:
#include<stdio.h>
int binario(int x, int bits)
{
int matriz[bits];
int resto=0,i=0;
float rest =0.0 ;
for(int i=0;i<8;i++)
{
resto = x/2;
rest = x%2;
x = resto;
if (rest>0)
{
matriz[i]=1;
}
else matriz[i]=0;
}
for(int j=bits-1;j>=0;j--)
{
printf("%d",matriz[j]);
}
printf("\n");
}
int main()
{
int num,bits;
bits = 8;
for (int i = 0; i < 256; i++)
{
num = binario(i,bits);
}
return 0;
}
Ecco la mia soluzione. Crea una maschera, iniziando con tutti gli 0 e un 1 nel bit più a sinistra, e logicamente la sposta a destra per ciascun bit nell'intero a 32 bit assunto . I bit vengono stampati in sequenza convertendo il valore dell'intero attualmente mascherato in un valore booleano.
void printBits(int val){
for(unsigned int mask = 0x80000000; mask; mask >>= 1){
printf("%d", !!(mask & val));
}
}
#include <stdio.h>
int main(void) {
int a,i,k=1;
int arr[32]; \\ taken an array of size 32
for(i=0;i <32;i++)
{
arr[i] = 0; \\initialised array elements to zero
}
printf("enter a number\n");
scanf("%d",&a); \\get input from the user
for(i = 0;i < 32 ;i++)
{
if(a&k) \\bit wise and operation
{
arr[i]=1;
}
else
{
arr[i]=0;
}
k = k<<1; \\left shift by one place evry time
}
for(i = 31 ;i >= 0;i--)
{
printf("%d",arr[i]); \\print the array in reverse
}
return 0;
}
void print_binary(int n) {
if (n == 0 || n ==1)
cout << n;
else {
print_binary(n >> 1);
cout << (n & 0x1);
}
}