Converting an integer to binary in C - c

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);
}

Related

Convert a float number to char array on C

I am trying to convert a float number to a char array.
sprintf() will not work for me and neither will dtostrf.
Since I have a limit in the decimal number (it is 5) I tried this:
int num = f;
int decimales = (f-num)*10000;
Everything worked fine until I typed the number 123.050. Instead of giving me the decimal part as "0.50" it gives me a 5000, because it does not count the 0 now that my "decimal" variable is an int.
Is there any other way to convert it?
You want a quick and dirty way to produce a string with the decimal representation of your float without linking sprintf because of space constraints on an embedded system. The number of decimals is fixed. Here is a proposal:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *ftoa(char *dest, size_t size, double val, int dec) {
char *p = dest;
char *q = dest + size;
long long mul = 1;
long long num;
int i;
if (size == 0)
return NULL;
*--q = '\0';
if (size == 1)
goto fail;
if (val < 0) {
val = -val;
if (p >= q)
goto fail;
*p++ = '-';
}
for (i = 0; i < dec; i++) {
mul *= 10;
}
num = (long long)(val * mul + 0.5);
for (i = 1; i < dec + 2 || num > 0; i++) {
if (p >= q)
goto fail;
*--q = '0' + (num % 10);
num = num / 10;
if (i == dec) {
if (p >= q)
goto fail;
*--q = '.';
}
}
memmove(p, q, dest + size - q);
return dest;
fail:
return memset(dest, '*', size - 1);
}
int main(int argc, char *argv[]) {
char buf[24];
for (int i = 1; i < argc; i++) {
double d = strtod(argv[i], NULL);
int dec = 5;
if (i + 1 < argc)
dec = atoi(argv[++i]);
printf("%s\n", ftoa(buf, sizeof buf, d, dec));
}
return 0;
}
Use %04d in printf()
const int D4 = 10000;
double f = 123.050;
int i = round(f*D4);
int num = i / D4;
int decimales = i % D4;
printf("%d.%04d\n", num, decimales);
gives
123.0500
If you worry about an int overflow (since we multiply the number by 10000), use long, or long long instead...
To save decimals in a string including the leading zero(es)
char sdec[5];
sprintf(sdec, "%04d", decimales);
sdec contains the decimals, including the leading zero.
(see also Is floating point math broken? )

Convert decimal to binary in C

I am trying to convert a decimal to binary such as 192 to 11000000. I just need some simple code to do this but the code I have so far doesn't work:
void dectobin(int value, char* output)
{
int i;
output[5] = '\0';
for (i = 4; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
}
Any help would be much appreciated!
The value is not decimal. All values in computer's memory are binary.
What you are trying to do is to convert int to a string using specific base.
There's a function for that, it's called itoa.
http://www.cplusplus.com/reference/cstdlib/itoa/
First of all 192cannot be represented in 4 bits
192 = 1100 0000 which required minimum 8 bits.
Here is a simple C program to convert Decimal number system to Binary number system
#include <stdio.h>
#include <string.h>
int main()
{
long decimal, tempDecimal;
char binary[65];
int index = 0;
/*
* Reads decimal number from user
*/
printf("Enter any decimal value : ");
scanf("%ld", &decimal);
/* Copies decimal value to temp variable */
tempDecimal = decimal;
while(tempDecimal!=0)
{
/* Finds decimal%2 and adds to the binary value */
binary[index] = (tempDecimal % 2) + '0';
tempDecimal /= 2;
index++;
}
binary[index] = '\0';
/* Reverse the binary value found */
strrev(binary);
printf("\nDecimal value = %ld\n", decimal);
printf("Binary value of decimal = %s", binary);
return 0;
}
5 digits are not enough for your example (192). Probably you should increase output
A few days ago, I was searching for fast and portable way of doing sprintf("%d", num). Found this implementation at the page itoa with GCC:
/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
It looks like this, but be careful, you have to reverse the resulting string :-)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char output[256]="";
int main()
{
int x= 192;
int n;
n = x;
int r;
do {
r = n % 2;
if (r == 1)
strcat(output,"1");
else strcat(output,"0");
n = n / 2;
}
while (n > 0);
printf("%s\n",output);
}
So... did you check the output of your code to understand why it doesn't work?
So iteration 1 of your loop:
value = 192
i = 4
output[i] = (11000000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 2 of your loop:
value = 96
i = 3
output[i] = (1100000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 3 of your loop:
value = 48
i = 2
output[i] = (110000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 4 of your loop:
value = 24
i = 1
output[i] = (11000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 5 of your loop:
value = 12
i = 0
output[i] = (1100 & 1) + '0' = 0 + 48 = 48 (char `0`)
Final string: "00000" and you wanted: "11000000"
See anything wrong with your code? Nope. Neither do I you just didn't go far enough. Change your output/loop to:
output[8] = '\0';
for (i = 7; i >= 0; --i, value >>= 1)
And then you'll have the correct result returned.
I would recomend just a more general approach, you're using a fixed length string, which limits you to binary numbers of a certian length. You might want to do something like:
loop while number dividing down is > 0
count number of times we loop
malloc an array the correct length and be returned
#include <stdio.h>
#include <stdlib.h>
void bin(int num) {
int n = num;
char *s = malloc(sizeof(int) * 8);
int i, c = 0;
printf("%d\n", num);
for (i = sizeof(int) * 8 - 1; i >= 0; i--) {
n = num >> i;
*(s + c) = (n & 1) ? '1' : '0';
c++;
}
*(s + c) = NULL;
printf("%s", s); // or you can also return the string s and then free it whenever needed
}
int main(int argc, char *argv[]) {
bin(atoi(argv[1]));
return EXIT_SUCCESS;
}
You can do it using while loop under a function also. I was just searching the solve for mine but the solves i get were not suitable, so I have done it accordingly the practical approach (divide using 2 until getting 0 and store the reminder in an array) and print the reverse of the array and Shared Here
#include <stdio.h>
int main()
{
long long int a,c;
int i=0,count=0;
char bol[10000];
scanf("%lld", &a);
c = a;
while(a!=0)
{
bol[i] = a%2;
a = a / 2;
count++;
i++;
}
if(c==0)
{
printf("0");
}
else
{
for(i=count-1; i>=0; i--)
{
printf("%d", bol[i]);
}
}
printf("\n");
return 0;
}
//C Program to convert Decimal to binary using Stack
#include<stdio.h>
#define max 100
int stack[max],top=-1,i,x;
void push (int x)
{
++top;
stack [top] = x;
}
int pop ()
{
return stack[top];
}
void main()
{
int num, total = 0,item;
print f( "Please enter a decimal: ");
scanf("%d",&num);
while(num > 0)
{
total = num % 2;
push(total);
num /= 2;
}
for(i=top;top>-1;top--)
{
item = pop ();
print f("%d",item);
}
}
Convert Decimal to Binary in C Language
#include<stdio.h>
void main()
{
long int n,n1,m=1,rem,ans=0;
printf("\nEnter Your Decimal No (between 0 to 1023) :: ");
scanf("%ld",&n);
n1=n;
while(n>0)
{
rem=n%2;
ans=(rem*m)+ans;
n=n/2;
m=m*10;
}
printf("\nYour Decimal No is :: %ld",n1);
printf("\nConvert into Binary No is :: %ld",ans);
}
This is the simplest way to do it
#include <stdio.h>
void main()
{
int n,i,j,sum=0;
printf("Enter a Decimal number to convert it to binary : ");
scanf("%d",&n);
for(i=n,j=1;i>=1;j*=10,i/=2)
sum+=(i%2)*j;
printf("\n%d",sum);
}
This is a simple program to convert a number from decimal to binary
#include <stdio.h>
#include <conio.h>
void decToBinary(int);
int main()
{
int number;
printf("Enter number to convert to binary: ");
scanf("%d", &number);
decToBinary(number);
return 0;
}
void decToBinary(int num)
{
if (num == 0)
{
return ;
}
decToBinary(num / 2);
printf("%d", num % 2);
}
Output of the Program:
Perhaps understanding the algorithm would allow you write or modify your own code to suit what you need. I do see that you don't have enough char array length to display your binary value for 192 though (You need 8 digits of binary, but your code only gives 5 binary digits)
Here's a page that clearly explains the algorithm.
I'm not a C/C++ programmer so here's my C# code contribution based on the algorithm example.
int I = 0;
int Q = 95;
string B = "";
while (Q != 0)
{
Debug.Print(I.ToString());
B += (Q%2);
Q = Q/2;
Debug.Print(Q.ToString());
I++;
}
Debug.Print(B);
All the Debug.Print is just to show the output.
//decimal to binary converter
long int dec2bin(unsigned int decimal_number){
if (decimal_number == 0)
return 0;
else
return ((decimal_number%2) + 10 * dec2bin(decimal_number/2));
}
number=215
a=str(int(number//128>=1))+str(int(number%128>=64))+
str(int(((number%128)%64)>=32))+str(int((((number%12
8)%64)%32)>=16))+str(int(((((number%128)%64)%32)%16)>=8))
+str(int(((((((number%128)%64)%32)%16)%8)>=4)))
+str(int(((((((((number%128)%64)%32)%16)%8)%4)>=2))))
+str(int(((((((((((number%128)%64)%32)%16)%8)%4)%2)>=1)))))
print(a)
You can also use the 'if', 'else', statements to write this code.
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system: ");
scanf("%d", &n);
printf("%d in binary number system is: ", n);
for (c = n; c > 0; c = c/2)
{
k = c % 2;//To
k = (k > 0) ? printf("1") : printf("0");
}
getch();
return 0;
}

Convert integer to string without access to libraries

I recently read a sample job interview question:
Write a function to convert an integer
to a string. Assume you do not have
access to library functions i.e.,
itoa(), etc...
How would you go about this?
fast stab at it: (edited to handle negative numbers)
int n = INT_MIN;
char buffer[50];
int i = 0;
bool isNeg = n<0;
unsigned int n1 = isNeg ? -n : n;
while(n1!=0)
{
buffer[i++] = n1%10+'0';
n1=n1/10;
}
if(isNeg)
buffer[i++] = '-';
buffer[i] = '\0';
for(int t = 0; t < i/2; t++)
{
buffer[t] ^= buffer[i-t-1];
buffer[i-t-1] ^= buffer[t];
buffer[t] ^= buffer[i-t-1];
}
if(n == 0)
{
buffer[0] = '0';
buffer[1] = '\0';
}
printf(buffer);
A look on the web for itoa implementation will give you good examples. Here is one, avoiding to reverse the string at the end. It relies on a static buffer, so take care if you reuse it for different values.
char* itoa(int val, int base){
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= base)
buf[i] = "0123456789abcdef"[val % base];
return &buf[i+1];
}
The algorithm is easy to see in English.
Given an integer, e.g. 123
divide by 10 => 123/10. Yielding, result = 12 and remainder = 3
add 30h to 3 and push on stack (adding 30h will convert 3 to ASCII representation)
repeat step 1 until result < 10
add 30h to result and store on stack
the stack contains the number in order of | 1 | 2 | 3 | ...
I would keep in mind that all of the digit characters are in increasing order within the ASCII character set and do not have other characters between them.
I would also use the / and the% operators repeatedly.
How I would go about getting the memory for the string would depend on information you have not given.
Assuming it is in decimal, then like this:
int num = ...;
char res[MaxDigitCount];
int len = 0;
for(; num > 0; ++len)
{
res[len] = num%10+'0';
num/=10;
}
res[len] = 0; //null-terminating
//now we need to reverse res
for(int i = 0; i < len/2; ++i)
{
char c = res[i]; res[i] = res[len-i-1]; res[len-i-1] = c;
}
An implementation of itoa() function seems like an easy task but actually you have to take care of many aspects that are related on your exact needs. I guess that in the interview you are expected to give some details about your way to the solution rather than copying a solution that can be found in Google (http://en.wikipedia.org/wiki/Itoa)
Here are some questions you may want to ask yourself or the interviewer:
Where should the string be located (malloced? passed by the user? static variable?)
Should I support signed numbers?
Should i support floating point?
Should I support other bases rather then 10?
Do we need any input checking?
Is the output string limited in legth?
And so on.
Convert integer to string without access to libraries
Convert the least significant digit to a character first and then proceed to more significant digits.
Normally I'd shift the resulting string into place, yet recursion allows skipping that step with some tight code.
Using neg_a in myitoa_helper() avoids undefined behavior with INT_MIN.
// Return character one past end of character digits.
static char *myitoa_helper(char *dest, int neg_a) {
if (neg_a <= -10) {
dest = myitoa_helper(dest, neg_a / 10);
}
*dest = (char) ('0' - neg_a % 10);
return dest + 1;
}
char *myitoa(char *dest, int a) {
if (a >= 0) {
*myitoa_helper(dest, -a) = '\0';
} else {
*dest = '-';
*myitoa_helper(dest + 1, a) = '\0';
}
return dest;
}
void myitoa_test(int a) {
char s[100];
memset(s, 'x', sizeof s);
printf("%11d <%s>\n", a, myitoa(s, a));
}
Test code & output
#include "limits.h"
#include "stdio.h"
int main(void) {
const int a[] = {INT_MIN, INT_MIN + 1, -42, -1, 0, 1, 2, 9, 10, 99, 100,
INT_MAX - 1, INT_MAX};
for (unsigned i = 0; i < sizeof a / sizeof a[0]; i++) {
myitoa_test(a[i]);
}
return 0;
}
-2147483648 <-2147483648>
-2147483647 <-2147483647>
-42 <-42>
-1 <-1>
0 <0>
1 <1>
2 <2>
9 <9>
10 <10>
99 <99>
100 <100>
2147483646 <2147483646>
2147483647 <2147483647>
The faster the better?
unsigned countDigits(long long x)
{
int i = 1;
while ((x /= 10) && ++i);
return i;
}
unsigned getNumDigits(long long x)
{
x < 0 ? x = -x : 0;
return
x < 10 ? 1 :
x < 100 ? 2 :
x < 1000 ? 3 :
x < 10000 ? 4 :
x < 100000 ? 5 :
x < 1000000 ? 6 :
x < 10000000 ? 7 :
x < 100000000 ? 8 :
x < 1000000000 ? 9 :
x < 10000000000 ? 10 : countDigits(x);
}
#define tochar(x) '0' + x
void tostr(char* dest, long long x)
{
unsigned i = getNumDigits(x);
char negative = x < 0;
if (negative && (*dest = '-') & (x = -x) & i++);
*(dest + i) = 0;
while ((i > negative) && (*(dest + (--i)) = tochar(((x) % 10))) | (x /= 10));
}
If you want to debug, You can split the conditions (instructions) into
lines of code inside the while scopes {}.
I came across this question so I decided to drop by the code I usually use for this:
char *SignedIntToStr(char *Dest, signed int Number, register unsigned char Base) {
if (Base < 2 || Base > 36) {
return (char *)0;
}
register unsigned char Digits = 1;
register unsigned int CurrentPlaceValue = 1;
for (register unsigned int T = Number/Base; T; T /= Base) {
CurrentPlaceValue *= Base;
Digits++;
}
if (!Dest) {
Dest = malloc(Digits+(Number < 0)+1);
}
char *const RDest = Dest;
if (Number < 0) {
Number = -Number;
*Dest = '-';
Dest++;
}
for (register unsigned char i = 0; i < Digits; i++) {
register unsigned char Digit = (Number/CurrentPlaceValue);
Dest[i] = (Digit < 10? '0' : 87)+Digit;
Number %= CurrentPlaceValue;
CurrentPlaceValue /= Base;
}
Dest[Digits] = '\0';
return RDest;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
char String[32];
puts(SignedIntToStr(String, -100, 16));
return 0;
}
This will automatically allocate memory if NULL is passed into Dest. Otherwise it will write to Dest.
Here's a simple approach, but I suspect if you turn this in as-is without understanding and paraphrasing it, your teacher will know you just copied off the net:
char *pru(unsigned x, char *eob)
{
do { *--eob = x%10; } while (x/=10);
return eob;
}
char *pri(int x, char *eob)
{
eob = fmtu(x<0?-x:x, eob);
if (x<0) *--eob='-';
return eob;
}
Various improvements are possible, especially if you want to efficiently support larger-than-word integer sizes up to intmax_t. I'll leave it to you to figure out the way these functions are intended to be called.
Slightly longer than the solution:
static char*
itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0)
n = -n;
i = 0;
do
{
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
return s;
}
Reverse:
int strlen(const char* str)
{
int i = 0;
while (str != '\0')
{
i++;
str++;
}
return i;
}
static void
reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
And although the decision davolno long here are some useful features for beginners. I hope you will be helpful.
This is the shortest function I can think of that:
Correctly handles all signed 32-bit integers including 0, MIN_INT32, MAX_INT32.
Returns a value that can be printed immediatelly, e.g.: printf("%s\n", GetDigits(-123))
Please comment for improvements:
static const char LARGEST_NEGATIVE[] = "-2147483648";
static char* GetDigits(int32_t x) {
char* buffer = (char*) calloc(sizeof(LARGEST_NEGATIVE), 1);
int negative = x < 0;
if (negative) {
if (x + (1 << 31) == 0) { // if x is the largest negative number
memcpy(buffer, LARGEST_NEGATIVE, sizeof(LARGEST_NEGATIVE));
return buffer;
}
x *= -1;
}
// storing digits in reversed order
int length = 0;
do {
buffer[length++] = x % 10 + '0';
x /= 10;
} while (x > 0);
if (negative) {
buffer[length++] = '-'; // appending minus
}
// reversing digits
for (int i = 0; i < length / 2; i++) {
char temp = buffer[i];
buffer[i] = buffer[length-1 - i];
buffer[length-1 - i] = temp;
}
return buffer;
}
//Fixed the answer from [10]
#include <iostream>
void CovertIntToString(unsigned int n1)
{
unsigned int n = INT_MIN;
char buffer[50];
int i = 0;
n = n1;
bool isNeg = n<0;
n1 = isNeg ? -n1 : n1;
while(n1!=0)
{
buffer[i++] = n1%10+'0';
n1=n1/10;
}
if(isNeg)
buffer[i++] = '-';
buffer[i] = '\0';
// Now we must reverse the string
for(int t = 0; t < i/2; t++)
{
buffer[t] ^= buffer[i-t-1];
buffer[i-t-1] ^= buffer[t];
buffer[t] ^= buffer[i-t-1];
}
if(n == 0)
{
buffer[0] = '0';
buffer[1] = '\0';
}
printf("%s", buffer);
}
int main() {
unsigned int x = 4156;
CovertIntToString(x);
return 0;
}
This function converts each digits of number into a char and chars add together
in one stack forming a string. Finally, string is formed from integer.
string convertToString(int num){
string str="";
for(; num>0;){
str+=(num%10+'0');
num/=10;
}
return str;
}

Convert binary format string to int, in C

How do I convert a binary string like "010011101" to an int, and how do I convert an int, like 5, to a string "101" in C?
The strtol function in the standard library takes a "base" parameter, which in this case would be 2.
int fromBinary(const char *s) {
return (int) strtol(s, NULL, 2);
}
(first C code I've written in about 8 years :-)
If it is a homework problem they probably want you to implement strtol, you would have a loop something like this:
char* start = &binaryCharArray[0];
int total = 0;
while (*start)
{
total *= 2;
if (*start++ == '1') total += 1;
}
If you wanted to get fancy you could use these in the loop:
total <<= 1;
if (*start++ == '1') total^=1;
I guess it really depends on some questions about your strings/program. If, for example, you knew your number wouldn't be bigger than 255 (IE you were only using 8 bits or 8 0s/1s), you could create a function where you hand it 8 bits from your string, traverse it and add to a sum that you returned everytime you hit a 1. IE if you hit the bit for 2^7 add 128 and the next bit you hit was 2^4 add 16.
This is my quick and dirty idea. I think more and Google for ya while at school. :D
For the 2nd part of the question, i.e. "how do I convert an int, like 5, to a string "101" in C?", try something like:
void
ltostr( unsigned long x, char * s, size_t n )
{
assert( s );
assert( n > 0 );
memset( s, 0, n );
int pos = n - 2;
while( x && (pos >= 0) )
{
s[ pos-- ] = (x & 0x1) ? '1' : '0'; // Check LSb of x
x >>= 1;
}
}
You can use the following coding
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
int nRC = 0;
int nCurVal = 1;
int sum = 0;
char inputArray[9];
memset(inputArray,0,9);
scanf("%s", inputArray);
// now walk the array:
int nPos = strlen(inputArray)-1;
while(nPos >= 0)
{
if( inputArray[nPos] == '1')
{
sum += nCurVal;
}
--nPos;
nCurVal *= 2;
}
printf( "%s converted to decimal is %d\n", inputArray, sum);
return nRC;
}
Use like this:
char c[20];
int s=23;
itoa(s,c,2);
puts(c);
Output:
10111
To answer the second part of the question.
char* get_binary_string(uint16_t data, unsigned char sixteen_bit)
{
char* ret = NULL;
if(sixteen_bit) ret = (char*)malloc(sizeof(char) * 17);
else ret = (char*)malloc(sizeof(char) * 9);
if(ret == NULL) return NULL;
if(sixteen_bit){
for(int8_t i = 15; i >= 0; i--){
*(ret + i) = (char)((data & 1) + '0');
data >>= 1;
}
*(ret + 16) = '\0';
return ret;
}else{
for(int8_t i = 7; i >= 0; i--){
*(ret + i) = (char)((data & 1) + '0');
data >>= 1;
}
*(ret + 8) = '\0';
return ret;
}
return ret;
}
To answer the first part of your question, here is a neat little function I created to convert Binary char strings to integers.
// Function used to change binary character strings to integers
int binToDec(char binCode[])
{
while (binCode != NULL)
{
int base = strlen(binCode) - 1; // the base of 2 to be multiplied, we start of -1 because we dont account for the last bit here
int sum = 0;
for (int i = 0; i < strlen(binCode) - 1; i++) // we do not account for the last bit of the binary code here....
{
int decimal = 1;
if (binCode[i] == '1')
{
for (int j = 0; j < base; j++) // we want to just multiply the number of true bits (not including the 1)
{
decimal = decimal * 2;
}
base = base - 1; // subtract base by 1 since we are moving down the string by 1
}
else // we encounter a zero
{
base = base - 1; // subtract a base multiple every time we encounter a zero...
continue; // carry on with the code
}
sum += decimal;
// starting from the left (higher power) to the end (lowest power or 1)
}
for (int j = strlen(binCode) - 1; j < strlen(binCode) + 1; j++)
{ // accounting for the endian bit that is always 1
if (binCode[j] == '1')
{
sum += 1; // add 1 to the sum total
}
}
return sum; // return the sum as an int
}
return 0;
}

Print an int in binary representation using C

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);
}
}

Resources