1
0
Fork 0
silvertech-scraps/checkbit.cpp

41 lines
1.1 KiB
C++

#include <stdlib.h>
#include <iostream>
#include <bitset>
/**
* Written by joe after feeling embarrased about the usage of & to find if
* a bit 'n' was 1 or 0.
**/
int main(int argc, char *argv[])
{
if(argc<3) // If the number of args is less than 3 then there were not enough expected args.
{
printf("\nPlease enter both an int and a [0-7] value to check that bit.");
exit(1); // Crash!
}
int BINARY_NUM = atoi(argv[1]); // Store that binary number (use ascci to int)
int BIT = atoi(argv[2]); // What bit to check
if(BINARY_NUM>254 || BIT>7)
{
printf("\nOne of your numbers was not formatted correctly, or out of range.");
exit(1); // Crash!
}
// Check the bit using <<
// Compares the number binary num using &, 1<<BIT should make a num like 0000 1000
if(BINARY_NUM & (1<<BIT))
{
printf("Bit number %d is SET in number %d.\n",BIT,BINARY_NUM);
}
else
{
printf("Bit number %d is not SET in number %d.\n",BIT,BINARY_NUM);
}
std::cout << "BIN = " << std::bitset<8>(BINARY_NUM) << std::endl; // Send the bitset to cout
std::cout << "BIT = " << std::bitset<8>(BIT) << std::endl; // Send the bitset to cout
return 0;
}