|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/jul15/binary.c
/*
A function that prints out the number in binary
*/
#include <stdio.h>
#include <stdlib.h>
void printBinaryNum(int num, int numBits);
int main(int argc, char *argv[]){
if(argc < 3){
printf("Usage: %s <number> <number of bits to print>\n", argv[0]);
exit(1);
}
int n, bits;
n = atoi(argv[1]);
bits = atoi(argv[2]);
printBinaryNum(n, bits);
return 0;
}
// 45 0010 1101
//this functiontakes in 2 arguments, the number we;re printing, and the number of bits we're printing
void printBinaryNum(int num, int numBits){
int bit;
//we start at the leftmost bit, then count down to bit 0.
//since we start counting our bits with the rightmost bit
//being bit 0, the leftmost bit will be bit (numBits-1).
for(int i = numBits -1; i >= 0; i--){
bit = (num >> i) & 1; //the number is right shifted "i" times, and then AND'ed with 1
if(bit == 1)
putchar('1');
else
putchar('0');
}
printf("\n");
}
|