Reputation: 1
How can I write a program that reads an integer and displays a binary number without using loops, just with binary operators? (Only with basic functions)
#include<stdio.h>
#include<stdint.h>
#include<math.h>
int main()
{uint8_t a;
scanf("%hhd", &a);
//i have read the integer, but I don't know how to go on
return 0;
}
Upvotes: 0
Views: 2248
Reputation: 2812
Displays a binary number without using loops, just with binary operators:
#include<stdio.h>
#include<stdint.h>
#include<math.h>
int main()
{
int a;
scanf("%u", &a);
printf("Number: 0x%X\n", a);
printf("%d", ((a & 0x80) >> 7));
printf("%d", ((a & 0x40) >> 6));
printf("%d", ((a & 0x20) >> 5));
printf("%d", ((a & 0x10) >> 4));
printf("%d", ((a & 0x08) >> 3));
printf("%d", ((a & 0x04) >> 2));
printf("%d", ((a & 0x02) >> 1));
printf("%d", ((a & 0x01) >> 0));
printf("\n");
return 0;
}
Be careful, as the input is integer, I added a printf
131
Number: 0x83
10000011
Of course, it would be easier with loops :
int main()
{
int a;
uint8_t Mask;
uint8_t Shift;
scanf("%u", &a);
printf("Number: %X\n", a);
Mask = 0x80;
Shift = 7;
while (Mask > 0)
{
printf("%d", ((a & Mask) >> Shift));
Mask = Mask >> 1;
Shift--;
}
printf("\n");
return 0;
}
Upvotes: 0