There is this neat piece of code on the next for converting a decimal value into hex, I can't quite figure out how it works, I was wondering if anyone could help.
My bitwise is a little flaky to say the least, but I'm eager to learn it. I was hoping some light shed on this might help me.Code:#include <iostream> using namespace std; int main() { int n; while (cin >> n) { cout << "decimal: " << n << endl; cout << "size of int: " << sizeof(int) << endl; //--- Print hex with leading zeros cout << "hex : "; for (int i=2*sizeof(int) - 1; i>=0; i--) { cout << "0123456789ABCDEF"[((n >> i*4) & 0xF)]; } cout << endl << endl; } return 0; }
The original source is Convert to Hex




Reply With Quote