C Concatenate int - c

I will be the first to admit, I'm a C# guy 100% and C isn't for me. However I have problem.
I need to concatenate 7 with HashUrl(HashInt) and then with HashInt
Any help would be greatly appreciated.
int main(int argc)
{
unsigned int HashInt;
HashInt = HashURL(argc);
// I need to return 7 + CheckHash(HashInt) + HashInt but not ADDING, but concanenating them
return HOWEVERTOGETTHESTRING;
}
I should have specified the usage of this. It's actually going to be used in a students VB6 project.
Private Declare Function main Lib "checksum.dll" (ByVal pStr As String) As Long
Private Sub Command1_Click()
MsgBox main("http://hello.com")
End Sub
The full source for the C library is
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <string.h>
#include <winreg.h>
#include <stdlib.h>
int StrToInt(char *pStr, int Init, int Factor)
{
while (*pStr) {
Init *= Factor;
Init += *pStr++;
}
return Init;
}
int HashURL(char *pStr)
{
unsigned int C1, C2, T1, T2;
C1 = StrToInt(pStr, 0x1505, 0x21);
C2 = StrToInt(pStr, 0, 0x1003F);
C1 >>= 2;
C1 = ((C1 >> 4) & 0x3FFFFC0) | (C1 & 0x3F);
C1 = ((C1 >> 4) & 0x3FFC00) | (C1 & 0x3FF);
C1 = ((C1 >> 4) & 0x3C000) | (C1 & 0x3FFF);
T1 = (C1 & 0x3C0) << 4;
T1 |= C1 & 0x3C;
T1 = (T1 << 2) | (C2 & 0xF0F);
T2 = (C1 & 0xFFFFC000) << 4;
T2 |= C1 & 0x3C00;
T2 = (T2 << 0xA) | (C2 & 0xF0F0000);
return (T1 | T2);
}
char CheckHash(unsigned int HashInt)
{
int Check = 0, Flag = 0;
int Remainder;
do {
Remainder = HashInt % 10;
HashInt /= 10;
if (1 == (Flag % 2) ){
Remainder += Remainder;
Remainder = (Remainder / 10) + (Remainder % 10);
}
Check += Remainder;
Flag ++;
} while( 0 != HashInt);
Check %= 10;
if (0 != Check) {
Check = 10 - Check;
if (1 == (Flag % 2)) {
if (1 == (Check % 2)) {
Check += 9;
}
Check >>= 1;
}
}
Check += 0x30;
return Check;
}
int main(int argc)
{
unsigned int HashInt;
int result;
HashInt = HashURL(argc);
char temp[100];
sprintf(temp, "7%i%j", CheckHash(HashInt), HashInt);
result = atoi(temp);
return result;
}
give " http://www.hello.com" should return 783544359868 but its not

You can use sprintf function to create formatted strings. To concatenate 3 integers into a string you could use something like
sprintf(string, "%d%d%d", int1, int2, int3)

I'm not all that great at C, but how I would solve this problem is to first turn them into character arrays, then concatenate those. Then you could turn the result back into an int:
int main(int argc) {
unsigned int HashInt;
int result;
HashInt = HashURL(argc);
char temp[50];
sprintf(temp, "7%i%i", CheckHash(HashInt), HashInt);
result = atoi(temp);
return result;
}
Note: No guarantees on this working...

For starters, you can look at:
asprintf
Just do man asprintf on a linux system.
Here's a link that has a simple example that you can adapt:
http://www.gnu.org/s/libc/manual/html_node/Dynamic-Output.html

Related

Is there a way to do a parity check using bit shifting, and without using xor of a string with bits?

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc == 2) {
int iParity = 0;
int bitmask = 0;
for (int i = 1; i < strlen(argv[1]); i++) {
switch (argv[1][i]) {
case '0':
if (iParity == 0)
iParity = 0;
else
iParity = 1;
break;
case '1':
if (iParity == 0)
iParity = 1;
else
iParity = 0;
break;
default:
break;
}
}
printf("The parity is: %d", iParity);
}
}
Basically I put the input directly into the execute line, like ./check 10010, check is the name of the program, and afterwards I need to put binary number, and I need to parity check the number using bit shifting ( << or >> ) and I SHOULD NOT use "xor" operator, is there a way to do that without really long code?
Here are 3 solutions without the use of exclusive or:
You can add the bit values directly from the string representation and use & to select the parity of the result:
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc == 2) {
const char *s = argv[1];
int iParity = 0 >> 0; // required bitshift :)
for (int i = 0; p[i] != '\0'; i++) {
iParity += p[i] == '1';
}
iParity &= 1;
printf("The parity is: %d\n", iParity);
}
return 0;
}
Your teacher might expect another approach, converting the number from text to an integer and computing the parity from its bits:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc == 2) {
// convert from base 2 text representation
unsigned long number = strtoul(argv[1], NULL, 2);
int iParity = 0;
while (number != 0) {
iParity += number & 1;
number = number >> 1;
}
iParity &= 1;
printf("The parity is: %d\n", iParity);
}
return 0;
}
Here is another one with fewer steps:
#include <stdio.h>
#include <stdlib.h>
int parity(unsigned long x) {
int result = 0 >>007<< 0; // zero, shaken not stirred
while (x) {
x &= x - 1;
result = 1 - result;
}
return result;
}
int main(int argc, char *argv[]) {
if (argc == 2) {
// convert from base 2 text representation
unsigned long number = strtoul(argv[1], NULL, 2);
int iParity = parity(number);
printf("The parity is: %d\n", iParity);
}
return 0;
}
Very naive - but no XOR's
int verynaive(uint32_t v)
{
int result = 0;
while(v)
{
result += v & 1;
v >>= 1;
}
return result & 1;
}
The fastest method I know is to use a lookup table.
int parity(uint32_t v)
{
uint16_t lookup = 0b110100110010110;
v ^= v >> 16;
v ^= v >> 8;
v ^= v >> 4;
return (lookup >> (v & 0x0f)) & 1;
}
or a bit more naive
int func( uint32_t x )
{
int32_t y;
for ( y=0; x; y = !y )
x ^= x & -x;
return y;
}
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if(argc == 2){
int iParity = 0;
char c;
int iSel = 0;
for (int i = 0; i < strlen(argv[1]); i++){
c = argv[1][i] - '0';
iSel = (iParity<<1) + c;
switch(iSel){
case 1:
case 2:
iParity = 1;
break;
case 0:
case 3:
iParity = 0;
break;
default:
break;
}
}
printf("Parity is: %d\n", iParity);
}
return 0;
}
Basically this is the solution my teacher told us in the out lesson, and yes, you had to convert a string index into a integer, and create a bit mask that works similar to a XOR operator, and that's pretty much it.
Addendum (by a commenter, scs):
The way the expression iSel = (iParity<<1) + c and the following switch statement work is that they implement the truth table for the XOR operator, like this:
iParity
c
shift expression
XOR output
0
0
0
0
0
1
1
1
1
0
2
1
1
1
3
0
In the end, the effect is the same as the much simpler
iParity = iParity ^ c;

Fixed point square root function wrong results for big numbers

Hello friends and enemies
I have this square root function from a library called libfixmath which works great, however from 32767.0f and above it starts returning wrong and negative results. The numbers I need square root of are rather big, up to 999999.0f. Any of you know what I could do to fix the problem?
#include <iostream>
float into_float(const int value) {
return ((float)value / 65536.0f);
}
int from_float(const float value) {
return (int)(value * 65536.0f);
}
int fp_sqrt(int value) {
unsigned char neg = (value < 0);
unsigned int num = (neg ? -value : value);
unsigned int result = 0;
unsigned int bit;
unsigned char n;
if (num & 0xFFF00000) {
bit = (unsigned int)1 << 30;
} else {
bit = (unsigned int)1 << 18;
}
while (bit > num) bit >>= 2;
for (n = 0; n < 2; n++) {
while (bit) {
if (num >= result + bit) {
num -= result + bit;
result = (result >> 1) + bit;
} else {
result = (result >> 1);
}
bit >>= 2;
}
if (n == 0) {
if (num > 65535) {
num -= result;
num = (num << 16) - 0x8000;
result = (result << 16) + 0x8000;
} else {
num <<= 16;
result <<= 16;
}
bit = 1 << 14;
}
}
if (num > result) {
result++;
}
return (neg ? -result : result);
}
void main() {
float flt_value = 32767.0f;
int int_value = from_float(flt_value);
float flt_root = sqrt(flt_value);
int int_root = fp_sqrt(int_value);
float flt_root2 = into_float(int_root);
printf("sqrt: %f fp_sqrt: %f", flt_root, flt_root2);
getchar();
}
Thank you leppie, I changed some stuff around and it works with big numbers now, I am not sure if what I did is totally right though but here it is:
#include <iostream>
float into_float(const int value) {
return ((float)value / 65536.0f);
}
long long from_float(const float value) {
return (long long)(value * 65536.0f);
}
long long fp_sqrt(long long value) {
unsigned char neg = (value < 0);
long long num = (neg ? -value : value);
long long result = 0;
long long bit;
unsigned char n;
if (num & 0xFFF00000) {
bit = (long long)1 << 60;
} else {
bit = (long long)1 << 36;
}
while (bit > num) bit >>= 2;
for (n = 0; n < 2; n++) {
while (bit) {
if (num >= result + bit) {
num -= result + bit;
result = (result >> 1) + bit;
} else {
result = (result >> 1);
}
bit >>= 2;
}
if (n == 0) {
if (num > 65535) {
num -= result;
num = (num << 16) - 0x8000;
result = (result << 16) + 0x8000;
} else {
num <<= 16;
result <<= 16;
}
bit = 1 << 14;
}
}
if (num > result) {
result++;
}
return (neg ? -result : result);
}
void main() {
float flt_value = 11932767.0f;
long long ll_value = from_float(flt_value);
float flt_root = sqrt(flt_value);
int int_root = (int)fp_sqrt(ll_value);
float flt_root2 = into_float(int_root);
printf("sqrt: %f fp_sqrt: %f", flt_root, flt_root2);
getchar();
}

How do I convert a char array [example 42] to the int equivilant [int 42] using bit manipulation?

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

Send a variable to a function and modify this variable in C

I have the following vars:
char seed[NBITS + 1], x0[NBITS + 1], y0[NBITS + 1], z0[NBITS + 1], dT0[NBITS + 1];
And i want to change it values on this function:
void lfsr(char *bin, char *output)
{
//bits significativos para fazer o xor NBITS -> NBITS,126,101,99;
int bits[4];
int bit;
if(bin[0] == '0')
bits[0] = 0;
else if(bin[0] == '1')
bits[0] = 1;
if(bin[2] == '0')
bits[1] = 0;
else if(bin[2] == '1')
bits[1] = 1;
if(bin[21] == '0')
bits[2] = 0;
else if(bin[21] == '1')
bits[2] = 1;
if(bin[19] == '0')
bits[3] = 0;
else if(bin[19] == '1')
bits[3] = 1;
bit = bits[0] ^ bits[1] ^ bits[2] ^ bits[3] ^ 1;
//reconstruir o vector de char depois do lfsr
for(int i = 127; i >= 1; i--)
{
bin[i] = bin[i - 1];
}
bin[0] = (char)(48 + bit);
output = bin;
}
The way that I put the value in y0 from x is, for example, calling the lfsr functions like this:
lfsr(x0, y0);
What am I doing wrong?
I have to do 3 Fibonacci Linear Feedback Shift Register starting from x0.
x0 = 10101010101010
y0 = lfsr(101010101010)
z0 = lfsr(y0)
dT0 = lfsr(z0);
The results are good, but when I do the above code the value of x0 will be the same as dT0 if i use pointers.
Can anyone help me?
Thanks. Cumps!
Consider the following:
The numbers correspond to the taps. The bits are actually 15..0, left to right. The following is my implementation of the Fibonacci Linear Feedback Shift Register:
#include <stdio.h>
uint16_t fibLfsr(const uint16_t num)
{
uint16_t tempNum;
tempNum = (num) ^ (num >> 2) ^ (num >> 3) ^ (num >> 5);
tempNum = (tempNum & 0x1) << 15;
tempNum = (tempNum | (num >> 1));
return tempNum;
}
int main(void)
{
uint16_t testNum = 0xACE1;
printf("%#X\n", testNum);
testNum = fibLfsr(testNum);
printf("%#X\n", testNum);
return 0;
}
I'm not quite sure why you're using strings and converting them to binary. If this is necessary, you'll need some of the standard library APIs in stdlib and string to convert the string to an uint16_t before calling fibLfsr() and back to a string afterwards.

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