I am trying to convert int to binary as string but I can not.
Please help me. How to convert integer to binary, please tell me.
Input: 32
Output: 00100000
My code:
#include <stdio.h>
#include <string.h>
char converttobinary(int n)
{
int i;
int a[8];
char op;
for (i = 0; i < 8; i++)
{
a[i] = n % 2;
n = (n - a[i]) / 2;
}
for (i = 7; i >= 0; i--)
{
op = strcat(op, a[i]);
}
return op;
}
int main()
{
int n;
char str;
n = 254;
str = converttobinary(n);
printf("%c", str);
return 0;
}
I have tried to modify your solution with minimal changes to make it work. There are elegant solutions to convert Integer to Binary for example using shift operators.
One of the main issue in the code was you were using character instead of character array.
i.e char str; instead of char str[SIZE];
Also you were performing string operations on a single character. Additionally, iostream header file is for C++.
There is room for lot of improvements in the solution posted below (I only made your code work with minimal changes).
My suggestion is to make your C basics strong and approach this problem again.
#include <stdio.h>
#include <string.h>
void converttobinary(int n, char *op)
{
int i;
int a[8];
for (i = 0; i < 8; i++)
{
a[i] = n % 2;
n = (n - a[i]) / 2;
}
for (i = 7; i >= 0; i--)
{
op[i]=a[i];
}
}
int main()
{
int n,i;
char str[8];
n = 8;
converttobinary(n,str);
for (i = 7; i >= 0; i--)
{
printf(" %d ",str[i]);
}
return 0;
}
char *rev(char *str)
{
char *end = str + strlen(str) - 1;
char *saved = str;
while(end > str)
{
int tmp = *str;
*str++ = *end;
*end-- = tmp;
}
return saved;
}
char *tobin(char *buff, unsigned long long data)
{
char *saved = buff;
while(data)
{
*buff++ = (data & 1) + '0';
data >>= 1;
}
*buff = 0;
return rev(saved);
}
int main()
{
char x[128];
unsigned long long z = 0x103;
printf("%llu is 0b%s\n", z, tobin(x, z));
return 0;
}
I modify your code a little bit to make what you want,
the result of this code with
n = 10
is
00001010
In this code i shift the bits n positions of the imput and compare if there is 1 or 0 in this position and write a '1' if there is a 1 or a '0' if we have a 0.
#include <stdio.h>
void converttobinary(int n, char op[8]){
int auxiliar = n;
int i;
for (i = 0; i < 8; i++) {
auxiliar = auxiliar >> i;
if (auxiliar & 1 == 1){
op[7-i] = '1';
} else{
op[7-i] = '0';
}
auxiliar = n;
}
}
int main (void){
int n = 10;
int i;
char op[8];
converttobinary(n, op);
for(i = 7; i > -1; i--){
printf("%c",op[i]);
}
return 0;
}
Taking an input as hex string and then converting it to char string in C. The hex string can contain 0x00 which translates to an 0 in Ascii when converted. This terminates the string. I have to store the value in an char string because the API uses that.
My code so far:
int hex_to_int(unsigned char c) {
int first =0;
int second =0;
int result=0;
if(c>=97 && c<=102)
c-=32;
first=c / 16 - 3;
second =c % 16;
result = first*10 + second;
if(result > 9) result--;
return result;
}
unsigned char hex_to_ascii(unsigned char c, unsigned char d){
unsigned char a='0';
int high = hex_to_int(c) * 16;
int low = hex_to_int(d);
a= high+low;
return a;
}
unsigned char* HextoString(unsigned char *st){
int length = strlen((const char*)st);
unsigned char* result=(unsigned char*)malloc(length/2+1);
unsigned char arr[500];
int i;
unsigned char buf = 0;
int j=0;
for(i = 0; i < length; i++)
{
if(i % 2 != 0)
{
arr[j++]=(unsigned char)hex_to_ascii(buf, st[i]);
}
else
{
buf = st[i];
}
}
arr[length/2+1]='\0';
memcpy(result,arr,length/2+1);
return result;
}
You can store any values in a char array. But if you want to store a value of 0x00, you cannot use the string functions on this array. So you have to use an integer variable to store the length of the data you want to store. You can then write functions that use this integer.
As you provided more information now, I can tell you that your function doesn't cut anything as it loops through the whole C-string which you provided for example as input "0a12345600a0020b12". The "problem" is that if you want to get the length (strlen()) of the output string after the conversion for example then it will stop at '\0' and you will get a "wrong" length in terms of your original input string.
It is exacly like it's written in the answer of Xaver save the length information and the string to work with that length and not the one you would get by the C-string functions like strlen().
To show that and in order to provide a right length information I've added a struct definition to your code that defines a string type consisting of a size_t len and an unsigned char* str called HexString. With the additional length information you can handle a 0 byte. Also I made little changes to your code, e.g. you don't need that character buffer arr on the stack.
With your input: "0a12345600a0020b12"
the following output you will see: <0a> <12> <34> <56> <00> <a0> <02> <0b> <12> <00>
if you print the C-string hexadecimal every single character. The last <00> is the null termination.
Look here on ideone for a live example.
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
size_t len; /* C-string length + '\0' */
unsigned char* str;
} HexString;
int hex_to_int(unsigned char c)
{
int first =0;
int second =0;
int result=0;
if (c >= 97 && c <= 102) /* 97 = 'a'; 102 = 'f' */
c -= 32;
first = c / 16 - 3;
second = c % 16;
result = first * 10 + second;
if (result > 9) result--;
return result;
}
unsigned char hex_to_ascii(unsigned char c, unsigned char d)
{
unsigned char a = '0';
int high = hex_to_int(c) * 16;
int low = hex_to_int(d);
a = high + low;
return a;
}
HexString HextoString(const char* const st)
{
HexString result;
size_t length = strlen(st);
result.len = length/2+1;
result.str = malloc(length/2+1);
size_t i;
size_t j = 0;
unsigned char buf = 0;
for (i = 0; i < length; i++)
{
if (i % 2 != 0)
{
result.str[j++] = hex_to_ascii(buf, st[i]);
}
else
{
buf = (unsigned char)st[i];
}
}
result.str[length/2+1] = '\0';
return result;
}
int main()
{
size_t i;
HexString hexString = HextoString("0a12345600a0020b12");
for (i = 0; i < hexString.len; ++i)
{
printf("<%02x> ", hexString.str[i]);
}
free(hexString.str);
return 0;
}
I'm trying to convert an ascii string to a binary string in C. I found this example Converting Ascii to binary in C but I rather not use a recursive function. I tried to write an iterative function as opposed to a recursive function, but the binary string is missing the leading digit. I'm using itoa to convert the string, however itoa is a non standard function so I used the implementation from What is the proper way of implementing a good "itoa()" function? , the one provided by Minh Nguyen.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int32_t ascii_to_binary(char *input, char **out, uint64_t len)
{
uint32_t i;
uint32_t str_len = len * 8;
if(len == 0)
{
printf("Length argument is zero\n");
return (-1);
}
(*out) = malloc(str_len + 1);
if((*out) == NULL)
{
printf("Can't allocate binary string: %s\n", strerror(errno));
return (-1);
}
if(memset((*out), 0, (str_len)) == NULL)
{
printf("Can't initialize memory to zero: %s\n", strerror(errno));
return (-1);
}
for(i = 0; i < len; i++)
itoa((int32_t)input[i], &(*out)[(i * 8)], 2);
(*out)[str_len] = '\0';
return (str_len);
}
int main(void)
{
int32_t rtrn = 0;
char *buffer = NULL;
rtrn = ascii_to_binary("a", &buffer, 1);
if(rtrn < 0)
{
printf("Can't convert string\n");
return (-1);
}
printf("str: %s\n", buffer);
return (0);
}
I get 1100001 for ascii character a, but I should get 01100001, so how do I convert the ascii string to the whole binary string?
You could change the for loop to something like this:
for(i = 0; i < len; i++) {
unsigned char ch = input[i];
char *o = *out + 8 * i;
int b;
for (b = 7; b >= 0; b--)
*o++ = (ch & (1 << b)) ? '1' : '0';
}
or similar:
for(i = 0; i < len; i++) {
unsigned char ch = input[i];
char *o = &(*out)[8 * i];
unsigned char b;
for (b = 0x80; b; b >>= 1)
*o++ = ch & b ? '1' : '0';
}
This program gets and integer ( which contains 32 bits ) and converts it to binary, Work on it to get it work for ascii strings :
#include <stdio.h>
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is:\n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("\n");
return 0;
}
Best just write a simple function to do this using bitwise operators...
#define ON_BIT = 0x01
char *strToBin(char c) {
static char strOutput[10];
int bit;
/*Shifting bits to the right, but don't want the output to be in reverse
* so indexing bytes with this...
*/
int byte;
/* Add a nul at byte 9 to terminate. */
strOutput[8] = '\0';
for (bit = 0, byte = 7; bit < 8; bit++, byte--) {
/* Shifting the bits in c to the right, each time and'ing it with
* 0x01 (00000001).
*/
if ((c >> bit) & BIT_ON)
/* We know this is a 1. */
strOutput[byte] = '1';
else
strOutput[byte] = '0';
}
return strOutput;
}
Something like that should work, there's loads of ways you can do it. Hope this helps.
i have an hex string and want it to be converted to ascii string in C. How can i accomplish this??
you need to take 2 (hex) chars at the same time... then calculate the int value
and after that make the char conversion like...
char d = (char)intValue;
do this for every 2chars in the hex string
this works if the string chars are only 0-9A-F:
#include <stdio.h>
#include <string.h>
int hex_to_int(char c){
int first = c / 16 - 3;
int second = c % 16;
int result = first*10 + second;
if(result > 9) result--;
return result;
}
int hex_to_ascii(char c, char d){
int high = hex_to_int(c) * 16;
int low = hex_to_int(d);
return high+low;
}
int main(){
const char* st = "48656C6C6F3B";
int length = strlen(st);
int i;
char buf = 0;
for(i = 0; i < length; i++){
if(i % 2 != 0){
printf("%c", hex_to_ascii(buf, st[i]));
}else{
buf = st[i];
}
}
}
Few characters like alphabets i-o couldn't be converted into respective ASCII chars .
like in string '6631653064316f30723161' corresponds to fedora . but it gives fedra
Just modify hex_to_int() function a little and it will work for all characters.
modified function is
int hex_to_int(char c)
{
if (c >= 97)
c = c - 32;
int first = c / 16 - 3;
int second = c % 16;
int result = first * 10 + second;
if (result > 9) result--;
return result;
}
Now try it will work for all characters.
strtol() is your friend here. The third parameter is the numerical base that you are converting.
Example:
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main(int argc, char **argv)
{
long int num = 0;
long int num2 =0;
char * str. = "f00d";
char * str2 = "0xf00d";
num = strtol( str, 0, 16); //converts hexadecimal string to long.
num2 = strtol( str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal.
printf( "%ld\n", num);
printf( "%ld\n", num);
}
If I understand correctly, you want to know how to convert bytes encoded as a hex string to its form as an ASCII text, like "537461636B" would be converted to "Stack", in such case then the following code should solve your problem.
Have not run any benchmarks but I assume it is not the peak of efficiency.
static char ByteToAscii(const char *input) {
char singleChar, out;
memcpy(&singleChar, input, 2);
sprintf(&out, "%c", (int)strtol(&singleChar, NULL, 16));
return out;
}
int HexStringToAscii(const char *input, unsigned int length,
char **output) {
int mIndex, sIndex = 0;
char buffer[length];
for (mIndex = 0; mIndex < length; mIndex++) {
sIndex = mIndex * 2;
char b = ByteToAscii(&input[sIndex]);
memcpy(&buffer[mIndex], &b, 1);
}
*output = strdup(buffer);
return 0;
}
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);
}
}