chundoong-lab-ta/SamsungDS22/HW1/main.cpp

76 lines
1.5 KiB
C++

#include <iostream>
void printIntAsBinary(int i)
{
using type_t = int;
using cast_type_t = unsigned int;
cast_type_t v = *((cast_type_t*)(&i));
unsigned int nbits = sizeof(type_t)*8;
for (int i = 0; i < nbits; i++) {
std::cout << ((v & (1ul << (nbits-1-i))) >> (nbits-1-i));
}
std::cout << "\n";
}
void printLongAsBinary(long l)
{
using type_t = long;
using cast_type_t = unsigned long;
cast_type_t v = *((cast_type_t*)(&l));
unsigned int nbits = sizeof(type_t)*8;
for (int i = 0; i < nbits; i++) {
std::cout << ((v & (1ul << (nbits-1-i))) >> (nbits-1-i));
}
std::cout << "\n";
}
void printFloatAsBinary(float f)
{
using type_t = float;
using cast_type_t = unsigned int;
cast_type_t v = *((cast_type_t*)(&f));
unsigned int nbits = sizeof(type_t)*8;
for (int i = 0; i < nbits; i++) {
std::cout << ((v & (1ul << (nbits-1-i))) >> (nbits-1-i));
}
std::cout << "\n";
}
void printDoubleAsBinary(double d)
{
using type_t = double;
using cast_type_t = unsigned long;
cast_type_t v = *((cast_type_t*)(&d));
unsigned int nbits = sizeof(type_t)*8;
for (int i = 0; i < nbits; i++) {
std::cout << ((v & (1ul << (nbits-1-i))) >> (nbits-1-i));
}
std::cout << "\n";
}
int main(int argc, char *argv[])
{
// 1. int
int i;
std::cin >> i;
// 2. long
long l;
std::cin >> l;
// 3. float
float f;
std::cin >> f;
// 4. double
double d;
std::cin >> d;
printIntAsBinary(i);
printLongAsBinary(l);
printFloatAsBinary(f);
printDoubleAsBinary(d);
return 0;
}