Skip to content

Instantly share code, notes, and snippets.

@jen6
Created March 9, 2017 11:24
Show Gist options
  • Select an option

  • Save jen6/073c60fdd1d4021f5d98ea2bec83a7ac to your computer and use it in GitHub Desktop.

Select an option

Save jen6/073c60fdd1d4021f5d98ea2bec83a7ac to your computer and use it in GitHub Desktop.
#include <iostream>
#include <bitset>
#include <cstring>
void printBin(int num)
{
unsigned char arr[4] = {0,};
char *ptr = reinterpret_cast<char *>(&num);
std::memcpy(arr, ptr, sizeof(int));
std::bitset<8> buf;
std::cout << " " << num << " : 0b";
for(auto i = 3; i >= 0; --i)
{
std::cout << std::bitset<8>(arr[i]);
}
std::cout << std::endl;
std::cout << "!" << num << " : 0b";
for(auto i = 3; i >=0; --i)
{
buf = std::bitset<8>(arr[i]);
std::cout << buf.flip();
}
std::cout << std::endl;
}
int main()
{
for(auto i = -5; i <= 5; ++i)
printBin(i);
}
@jen6

jen6 commented Mar 9, 2017

Copy link
Copy Markdown
Author

How to Compile
g++ -std=c++11 -o negative negative.cpp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment