bit manipulation - c++ bit operations how to print out 16, 32 bits -
at moment have script prints out numeric values bits example
print((short) 1); i value of 00000001, how can value 00000001 00000000 , in case if print print((int) 1); value of 00000001 00000000 00000000 00000000. here code:
void printbyte(unsigned char x) { (int = 0; < 8; i++) { if (x & 0x80) cout << 1; else cout << 0; x = x << 1; } cout << endl; } template <typename t> void print (t a) { unsigned char *p = (unsigned char *) &a; printbyte(*p); } int main() { print((short) 1); system("pause"); return 0; }
you can use sizeof(t) within print determine how many bytes process , call printbyte each byte, e.g.
#include <iostream> #include <climits> using namespace std; void printbyte(unsigned char x) { (int = 0; < char_bit; i++) { cout << ((x & 0x80) != 0); x <<= 1; } } template <typename t> void print (t a) { (size_t = 0; < sizeof(t); ++i) { unsigned char b = >> ((sizeof(t) - - 1) * char_bit); //unsigned char b = >> (i * char_bit); // use little endian output printbyte(b); cout << " "; } cout << endl; } int main() { print((short) 1); print((long long) 42); return 0; }
Comments
Post a Comment