Related
I'm a beginner in C and below is a program to find the position of a given digit. My first function works but i can't say the same for the 2nd one(digitPos2) that returns the value from a pointer. I'm not sure what is wrong and why.
#include <stdio.h>
int digitPos1(int num, int digit);
void digitPos2(int num, int digit, int *result);
int main()
{
int number, digit, result=0;
printf("Enter the number: \n");
scanf("%d", &number);
printf("Enter the digit: \n");
scanf("%d", &digit);
printf("digitPos1(): %d\n", digitPos1(number, digit));
digitPos2(number, digit, &result);
printf("digitPos2(): %d\n", result);
main();//return 0;
}
int digitPos1(int num, int digit)
{
int pos=0;
while(num)
{
if(num%10 == digit)
{
return pos = pos + 1;
}
else
{
pos++;
num = num/10;
}
}
}
void digitPos2(int num, int digit, int *result)
{
int pos=0;
while(num)
{
if(num%10 == digit)
{
pos = pos + 1;
*result = pos;
}
else
{
pos++;
num = num/10;
}
}
*result = 0;
}
Output
The both functions are invalid.
For starters it is better to set the parameters num and digit as having the type unsigned int. Otherwise the functions will be more complicated. That is you will need to check whether one of the parameters or both are negative.
Secondly the function digitPos1 has undefined behavior because it returns nothing in case when the digit is not present in the number.
Moreover instead of the while loop you should use a do-while loop because num can be set by the user to 0 and 0 is a valid number.
This statement in the function digitPos2
*result = 0;
does not make sense.
And you have to exut the function if the digit is found
while(num)
{
if(num%10 == digit)
{
pos = pos + 1;
*result = pos;
// exit the function
}
//...
Also it is unclear how the user can determine whether the digit is not present in the number.
You can use an approach that returns for example -1 in case the digit is not present in the number.
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
Here is a demonstrative program
#include <stdio.h>
int digitPos1( unsigned int num, unsigned int digit);
void digitPos2( unsigned int num, unsigned int digit, int *result);
int main( void )
{
unsigned int number, digit;
int result;
printf( "Enter the number: " );
scanf( "%d", &number );
printf( "Enter the digit: " );
scanf( "%d", &digit );
printf("digitPos1(): %d\n", digitPos1( number, digit ) );
digitPos2(number, digit, &result);
printf( "digitPos2(): %d\n", result );
return 0;
}
int digitPos1( unsigned int num, unsigned int digit )
{
const unsigned int Base = 10;
int pos = -1;
int n = 0;
do
{
if ( num % Base == digit )
{
pos = n;
}
else
{
++n;
}
} while ( ( num /= Base ) && ( pos == -1 ) );
return pos;
}
void digitPos2( unsigned int num, unsigned int digit, int *result )
{
const unsigned int Base = 10;
int n = 0;
*result = -1;
do
{
if ( num % Base == digit )
{
*result = n;
}
else
{
++n;
}
} while ( ( num /= Base ) && ( *result == -1 ) );
}
The program output might look for example like
Enter the number: 123456
Enter the digit: 2
digitPos1(): 4
digitPos2(): 4
The position startrs from 0.
First of all,
In case the digit is not present at all you should return a index that is not possible in a real number, e.g. you can return a negative number in that case, may be -1. (In c/c++ indexing starts from 0 so 0 is always a valid index)
so for digitPos1(int num, int digit) the ending should look like
while(num){
//your code
//return pos + 1 in case digit found
//more code
}
return -1;
similarly for digitPos2(int num, int digit, int *result) you should initialize *result with -1
int pos=0;
*result = -1;
and the biggest mistake is to set *result=0 at the end. To understand this you should understand that while dealing with pointers, every change you make to the pointers value is reflected in the callee function also, so if you set *result=0 then all the previous computation is just wasted and the position is returned blindly as 0. So you MUST remove this line for your computations to reflect back in the main function.
Secondly,
I don't think you have considered the cases of duplicates, e.g.
num : 1232323
digit : 3
Here, ideally you should break or return after you have found the match in case of digitPos2
*result = pos;
return; //return type is void
This changes should give expected behaviour according to me.
I don't know how to proceed with this...
I want to change a binary stored as an int 1111 to 111 being stored as an int also?
I don't ordinarily answer "gimme teh codez" questions, but it was an
interesting problem so I did it for fun. As usual, most of the time went
into extraneous stuff like the output code.
If this is homework, do take the time to understand how the code
works, or you'll only be cheating yourself.
#include <stdio.h>
#include <string.h>
// Define "number" as an unsigned number of desired size
typedef unsigned long number;
number drop_msb(number n);
char *ntob(char *dest, number n, int min_len);
int main()
{
number i;
number j;
char ibuf[65];
char jbuf[65];
for (i = 0; i < 512; i++) {
j = drop_msb(i);
ntob(ibuf, i, 0);
ntob(jbuf, j, strlen(ibuf) - 1);
printf("%s --> %s\n", ibuf, jbuf);
}
return 0;
}
number drop_msb(number n)
{
number bit;
number a;
// Handle special case
if (n == 0)
return 0;
// Set highest bit
bit = ((number) -1 >> 1) ^ (number) -1;
// Guaranteed to terminate
while (1) {
a = n ^ bit;
if (a < n)
return a;
bit >>= 1;
}
}
char *ntob(char *dest, number n, int min_len)
{
/* Convert n to shortest binary string, padding with zeroes on left
* to make it at least min_len characters long. dest should be long
* enough to hold the maximum number, plus terminating null. */
char *left;
char *right;
/* min_len should be >= 1, to handle n == 0 correctly. Also needs to
* be non-negative to avoid bad pointer during padding. */
if (min_len < 1)
min_len = 1;
// Build with lsb on left
for (right = dest; n; right++, n >>= 1)
*right = '0' | (n & 1);
// Pad if needed
while (right < dest + min_len)
*right++ = '0';
*right = '\0';
// Reverse it
for (left = dest, right--; left < right; left++, right--) {
*left ^= *right;
*right ^= *left;
*left ^= *right;
}
return dest;
}
unsigned int test(unsigned int n)
{
unsigned int answer = 1;
while(n>>=1 && n)
{
answer <<= 1;
}
answer = (answer-1);
return answer;
}
This should solve your problem.
say I have a string 42\0 0b0011010000110001000000000 [or an array without a null terminator 42 0b00110100001100010] and I want to convert it to 42 0b00101010 with bit manipulation. How would I go about this?
In a nutshell, without any checks that the number is a digit, is negative, or will be out of range, you can do this:
int myatoi( const char * s )
{
int result = 0;
while( *s )
{
result <<= 1;
result += (result << 2);
result += (*s++ & 0x0f);
}
return result;
}
Caveat: The use of addition doesn't strictly meet the requirement that this be achieved with bit operations.
Adding on to #paddy 's answer, for a purely bitwise way to accomplish this is this:
#include <stdio.h>
int bitwiseadd(int x, int y);
int main(int argc, char **argv)
{
char *array = argv[1];
int result = 0;
while(*array)
{
result <<= 1;
result = bitwiseadd(result, result<<2);
result = bitwiseadd(result, *array++ & 0x0f);
}
printf("Value is:%d.\n", result);
return 0;
}
int bitwiseadd(int x, int y)
{
if( y == 0 )
return x;
else
return bitwiseadd(x^y,(x&y)<<1);
}
I believe this is the answer.
First we need to strip the 0010 off the top, as in the ASCII table the binary of the char is 0010+the binary value of the number, 1 is 00100001 etc
So, you would do
00001111 & char;
so
int tmpValue = 15 & char;
Next, you would get the size of the array.
int n = strlen(chararray);
working left to right of the array
#include <stdio.h>
#include <string.h>
int main(void)
{
char array[4] = "123\0";
int total = 0;
int index;
int arraysize = strlen(array);
for(index=0; index < arraysize; index++)
{
total = ((total << 3) + (total << 1));
total += (15 & array[index]);
}
printf("Value is: %d", total);
return 0;
}
I'm trying to convert an integer 10 into the binary number 1010.
This code attempts it, but I get a segfault on the strcat():
int int_to_bin(int k)
{
char *bin;
bin = (char *)malloc(sizeof(char));
while(k>0) {
strcat(bin, k%2);
k = k/2;
bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));
}
bin[sizeof(bin)-1] = '\0';
return atoi(bin);
}
How do I convert an integer to binary in C?
If you want to transform a number into another number (not number to string of characters), and you can do with a small range (0 to 1023 for implementations with 32-bit integers), you don't need to add char* to the solution
unsigned int_to_int(unsigned k) {
if (k == 0) return 0;
if (k == 1) return 1; /* optional */
return (k % 2) + 10 * int_to_int(k / 2);
}
HalosGhost suggested to compact the code into a single line
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
You need to initialise bin, e.g.
bin = malloc(1);
bin[0] = '\0';
or use calloc:
bin = calloc(1, 1);
You also have a bug here:
bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));
this needs to be:
bin = (char *)realloc(bin, sizeof(char) * (strlen(bin)+1));
(i.e. use strlen, not sizeof).
And you should increase the size before calling strcat.
And you're not freeing bin, so you have a memory leak.
And you need to convert 0, 1 to '0', '1'.
And you can't strcat a char to a string.
So apart from that, it's close, but the code should probably be more like this (warning, untested !):
int int_to_bin(int k)
{
char *bin;
int tmp;
bin = calloc(1, 1);
while (k > 0)
{
bin = realloc(bin, strlen(bin) + 2);
bin[strlen(bin) - 1] = (k % 2) + '0';
bin[strlen(bin)] = '\0';
k = k / 2;
}
tmp = atoi(bin);
free(bin);
return tmp;
}
Just use itoa to convert to a string, then use atoi to convert back to decimal.
unsigned int_to_int(unsigned int k) {
char buffer[65]; /* any number higher than sizeof(unsigned int)*bits_per_byte(8) */
return atoi( itoa(k, buffer, 2) );
}
The working solution for Integer number to binary conversion is below.
int main()
{
int num=241; //Assuming 16 bit integer
for(int i=15; i>=0; i--) cout<<((num >> i) & 1);
cout<<endl;
for(int i=0; i<16; i++) cout<<((num >> i) & 1);
cout<<endl;
return 0;
}
You can capture the cout<< part based on your own requirement.
Well, I had the same trouble ... so I found this thread
I think the answer from user:"pmg" does not work always.
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
Reason: the binary representation is stored as an integer. That is quite limited.
Imagine converting a decimal to binary:
dec 255 -> hex 0xFF -> bin 0b1111_1111
dec 1023 -> hex 0x3FF -> bin 0b11_1111_1111
and you have to store this binary representation as it were a decimal number.
I think the solution from Andy Finkenstadt is the closest to what you need
unsigned int_to_int(unsigned int k) {
char buffer[65]; // any number higher than sizeof(unsigned int)*bits_per_byte(8)
return itoa( atoi(k, buffer, 2) );
}
but still this does not work for large numbers.
No suprise, since you probably don't really need to convert the string back to decimal. It makes less sense. If you need a binary number usually you need for a text somewhere, so leave it in string format.
simply use itoa()
char buffer[65];
itoa(k, buffer, 2);
You can use function this function to return char* with string representation of the integer:
char* itob(int i) {
static char bits[8] = {'0','0','0','0','0','0','0','0'};
int bits_index = 7;
while ( i > 0 ) {
bits[bits_index--] = (i & 1) + '0';
i = ( i >> 1);
}
return bits;
}
It's not a perfect implementation, but if you test with a simple printf("%s", itob(170)), you'll get 01010101 as I recall 170 was. Add atoi(itob(170)) and you'll get the integer but it's definitely not 170 in integer value.
You could use this function to get array of bits from integer.
int* num_to_bit(int a, int *len){
int arrayLen=0,i=1;
while (i<a){
arrayLen++;
i*=2;
}
*len=arrayLen;
int *bits;
bits=(int*)malloc(arrayLen*sizeof(int));
arrayLen--;
while(a>0){
bits[arrayLen--]=a&1;
a>>=1;
}
return bits;
}
void intToBin(int digit) {
int b;
int k = 0;
char *bits;
bits= (char *) malloc(sizeof(char));
printf("intToBin\n");
while (digit) {
b = digit % 2;
digit = digit / 2;
bits[k] = b;
k++;
printf("%d", b);
}
printf("\n");
for (int i = k - 1; i >= 0; i--) {
printf("%d", bits[i]);
}
}
You can convert decimal to bin, hexa to decimal, hexa to bin, vice-versa etc by following this example.
CONVERTING DECIMAL TO BIN
int convert_to_bin(int number){
int binary = 0, counter = 0;
while(number > 0){
int remainder = number % 2;
number /= 2;
binary += pow(10, counter) * remainder;
counter++;
}
}
Then you can print binary equivalent like this:
printf("08%d", convert_to_bin(13)); //shows leading zeros
Result in string
The following function converts an integer to binary in a string (n is the number of bits):
// Convert an integer to binary (in a string)
void int2bin(unsigned integer, char* binary, int n=8)
{
for (int i=0;i<n;i++)
binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
binary[n]='\0';
}
Test online on repl.it.
Source : AnsWiki.
Result in string with memory allocation
The following function converts an integer to binary in a string and allocate memory for the string (n is the number of bits):
// Convert an integer to binary (in a string)
char* int2bin(unsigned integer, int n=8)
{
char* binary = (char*)malloc(n+1);
for (int i=0;i<n;i++)
binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
binary[n]='\0';
return binary;
}
This option allows you to write something like printf ("%s", int2bin(78)); but be careful, memory allocated for the string must be free later.
Test online on repl.it.
Source : AnsWiki.
Result in unsigned int
The following function converts an integer to binary in another integer (8 bits maximum):
// Convert an integer to binary (in an unsigned)
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
Test online on repl.it
Display result
The following function displays the binary conversion
// Convert an integer to binary and display the result
void int2bin(unsigned integer, int n=8)
{
for (int i=0;i<n;i++)
putchar ( (integer & (int)1<<(n-i-1)) ? '1' : '0' );
}
Test online on repl.it.
Source : AnsWiki.
You can add the functions to the standard library and use it whenever you need.
Here is the code in C++
#include <stdio.h>
int power(int x, int y) //calculates x^y.
{
int product = 1;
for (int i = 0; i < y; i++)
{
product = product * x;
}
return (product);
}
int gpow_bin(int a) //highest power of 2 less/equal to than number itself.
{
int i, z, t;
for (i = 0;; i++)
{
t = power(2, i);
z = a / t;
if (z == 0)
{
break;
}
}
return (i - 1);
}
void bin_write(int x)
{
//printf("%d", 1);
int current_power = gpow_bin(x);
int left = x - power(2, current_power);
int lower_power = gpow_bin(left);
for (int i = 1; i < current_power - lower_power; i++)
{
printf("0");
}
if (left != 0)
{
printf("%d", 1);
bin_write(left);
}
}
void main()
{
//printf("%d", gpow_bin(67));
int user_input;
printf("Give the input:: ");
scanf("%d", &user_input);
printf("%d", 1);
bin_write(user_input);
}
#define BIT_WIDTH 32
char *IntToBin(unsigned n, char *buffer) {
char *ptr = buffer + BIT_WIDTH;
do {
*(--ptr) = (n & 1) + '0';
n >>= 1;
} while(n);
return ptr;
}
#define TEST 1
#if TEST
#include <stdio.h>
int main() {
int n;
char buff[BIT_WIDTH + 1];
buff[BIT_WIDTH] = '\0';
while(scanf("%d", &n) == 1)
puts(IntToBin(n, buff));
return 0;
}
#endif
short a;
short b;
short c;
short d;
short e;
short f;
short g;
short h;
int i;
char j[256];
printf("BINARY CONVERTER\n\n\n");
//uses <stdlib.h>
while(1)
{
a=0;
b=0;
c=0;
d=0;
e=0;
f=0;
g=0;
h=0;
i=0;
gets(j);
i=atoi(j);
if(i>255){
printf("int i must not pass the value 255.\n");
i=0;
}
if(i>=128){
a=1;
i=i-128;}
if(i>=64){
b=1;
i=i-64;}
if(i>=32){
c=1;
i=i-32;}
if(i>=16){
d=1;
i=i-16;}
if(i>=8){
e=1;
i=i-8;}
if(i>=4){
f=1;
i=i-4;}
if(i>=2){
g=1;
i=i-2;}
if(i>=1){
h=1;
i=i-1;}
printf("\n%d%d%d%d%d%d%d%d\n\n",a,b,c,d,e,f,g,h);
}
I'm looking for a function to allow me to print the binary representation of an int. What I have so far is;
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;
}
But when I call
printf("a %s",int2bin(aMask)) // aMask = 0xFF000000
I get output like;
0000000000000000000000000000000000xtpYy (And a bunch of unknown characters.
Is it a flaw in the function or am I printing the address of the character array or something? Sorry, I just can't see where I'm going wrong.
NB The code is from here
EDIT: It's not homework FYI, I'm trying to debug someone else's image manipulation routines in an unfamiliar language. If however it's been tagged as homework because it's an elementary concept then fair play.
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);
}
A few suggestions:
null-terminate your string
don't use magic numbers
check the return value of malloc()
don't cast the return value of malloc()
use binary operations instead of arithmetic ones as you're interested in the binary representation
there's no need for looping twice
Here's the code:
#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;
}
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);
Here is a simple algorithm.
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;
}
}
this is what i made to display an interger as a binairy code it is separated per 4 bits:
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++;
}
it could be a bit big but i always write it in a way (i hope) that everyone can understand what is going on. hope this helped.
#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");
}
}
Just a enhance of the answer from #Adam Markowitz
To let the function support uint8 uint16 uint32 and uint64:
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
// Convert integer number to binary representation.
// The buffer must have bits bytes length.
void int2bin(uint64_t number, uint8_t *buffer, int bits) {
memset(buffer, '0', bits);
buffer += bits - 1;
for (int i = bits - 1; i >= 0; i--) {
*buffer-- = (number & 1) + '0';
number >>= 1;
}
}
int main(int argc, char *argv[]) {
char buffer[65];
buffer[8] = '\0';
int2bin(1234567890123, buffer, 8);
printf("1234567890123 in 8 bits: %s\n", buffer);
buffer[16] = '\0';
int2bin(1234567890123, buffer, 16);
printf("1234567890123 in 16 bits: %s\n", buffer);
buffer[32] = '\0';
int2bin(1234567890123, buffer, 32);
printf("1234567890123 in 32 bits: %s\n", buffer);
buffer[64] = '\0';
int2bin(1234567890123, buffer, 64);
printf("1234567890123 in 64 bits: %s\n", buffer);
return 0;
}
The output:
1234567890123 in 8 bits: 11001011
1234567890123 in 16 bits: 0000010011001011
1234567890123 in 32 bits: 01110001111110110000010011001011
1234567890123 in 64 bits: 0000000000000000000000010001111101110001111110110000010011001011
Two things:
Where do you put the NUL character? I can't see a place where '\0' is set.
Int is signed, and 0xFF000000 would be interpreted as a negative value. So while (a > 0) will be false immediately.
Aside: The malloc function inside is ugly. What about providing a buffer to int2bin?
A couple of things:
int f = 32;
int i = 1;
do{
str[--f] = i^a?'1':'0';
}while(i<<1);
It's highly platform dependent, but
maybe this idea above gets you started.
Why not use memset(str, 0, 33) to set
the whole char array to 0?
Don't forget to free()!!! the char*
array after your function call!
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;
}
//This is what i did when our teacher asked us to do this
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);
}
the simplest way for me doing this (for a 8bit representation):
#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;
}
Here is another solution that does not require a char *.
#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);
}
Or here for more readability:
#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');
}
And here is the 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;
}
Not so elegant, but accomplishes your goal and it is very easy to understand:
#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;
}
#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);
}
}