Write a function to convert an integer into a bit string. For example, if input is 2, the output is "00000000000000000000000000000010" if the system is 32-bit, "0000000000000010" if the system is 16-bit and so on.
Strategy:
We will use bitwise manipulation and convert one bit at a time to character. We look at the right most bit and if it is a 0 bit, we add '0' character into our bit string. Otherwise, we add '1' character into our bit string.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BITS_PER_BYTE 8
char* int2bin(int num)
{
int bitStrLen = sizeof(int) * BITS_PER_BYTE * sizeof(char)+1;
char* p = (char*)malloc(bitStrLen);
for (int i = (bitStrLen-1); i >= 0; i--)
{
if(i==bitStrLen-1)
*(p+i)='\0';
else
{
int k = 1 & num;
*(p + i) = ((k == 1) ? '1' : '0');
num >>= 1;}
}
return p;
}
int main()
{
int num=156;
size_t count=sizeof(int) * BITS_PER_BYTE * sizeof(char);
char *str=(char*)malloc(count);
memset (str,0,count);
str=int2bin(num);
printf(" The string format is %s\n",str);
getchar();
return 0;
}
Strategy:
We will use bitwise manipulation and convert one bit at a time to character. We look at the right most bit and if it is a 0 bit, we add '0' character into our bit string. Otherwise, we add '1' character into our bit string.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BITS_PER_BYTE 8
char* int2bin(int num)
{
int bitStrLen = sizeof(int) * BITS_PER_BYTE * sizeof(char)+1;
char* p = (char*)malloc(bitStrLen);
for (int i = (bitStrLen-1); i >= 0; i--)
{
if(i==bitStrLen-1)
*(p+i)='\0';
else
{
int k = 1 & num;
*(p + i) = ((k == 1) ? '1' : '0');
num >>= 1;}
}
return p;
}
int main()
{
int num=156;
size_t count=sizeof(int) * BITS_PER_BYTE * sizeof(char);
char *str=(char*)malloc(count);
memset (str,0,count);
str=int2bin(num);
printf(" The string format is %s\n",str);
getchar();
return 0;
}
No comments:
Post a Comment