I'm just testing some ideas for accessing the bytes and bits of an integer. Everything works, the only problem is that I get an infinite loop if I enter a value greater than what an int can hold, like 4,300,000,000. The 'if' statement on line 24 doesn't seem to catch it.
#include <iostream>
#include <bitset>
usingnamespace std;
#define num unsigned int
#define let unsigned char
int main() {
while (true) { //begin loop
num x = 0;
cout << "Press 1 to break or 2 to continue ";
cin >> x;
if (x == 1) break;
//create an integer and a char array in a union
union {
num y = 0;
let a[4];
};
//get a value for y
cout << endl << endl << "Enter a value between 0 and 4,294,967,295" << endl;
cin >> y;
if(cin.fail()) cin.clear();
//output the bytes of y as unsigned integers big-endian
cout << (num)a[3] << " ";
cout << (num)a[2] << " ";
cout << (num)a[1] << " ";
cout << (num)a[0] << " ";
cout << endl << endl;
//create a pointer to y
let* p = (let*)&y;
//output the bits of each byte of y big-endian
bitset<8> four(*(p + 3));
cout << four << " "; //4th byte of the integer
bitset<8> three(*(p + 2));
cout << three << " "; //3rd byte of the integer
bitset<8> two(*(p + 1));
cout << two << " "; //2nd byte of the integer
bitset<8> one(*p);
cout << one << " "; //1st byte of the integer
cout << endl << endl;
//using a for loop to output the bytes of y as integers big-endian
for (int i = 3; i >= 0; i--) {
cout << (num)*(p + i) << " ";
} //end for
cout << endl << endl;
} //end loop
return 0;
} //end main
You should be able to copy and paste this text into an empty .cpp file in Visual Studio 2015 Community Edition and run it (F5).
Compilation with cpp.sh (The gear icon top left of the code) with all 3 warnings on:
In function 'int main()':
24:14: warning: comparison of unsigned expression < 0 is always false [-Wtype-limits]
24:23: warning: comparison is always false due to limited range of data type [-Wtype-limits]
Let the compiler work for you.
1 2
#define num unsigned int
#define let unsigned char
Don't do that, it just provides obfuscation.
What is the point if checking for < 0 , when the type is unsigned ?
If you need to test for negative values, you need to use a datatype capable of holding negative values.
All values will be in the range 0 to 4294967295 (for a 32-bit unsigned integer), so testing for anything outside that range won't work.
The reason for the infinite loop is that if the entered value is too large, the cin stream will have the fail() flag set. Before continuing with another cin operation, you'd need to clear the flag. Or quit from the loop, if that is your preference.
1 2 3 4 5
cin >> y;
if (!cin)
{
cin.clear(); // reset flags after invalid input
}
You might also want to trap non-numeric input, which could also cause problems.
1 2 3 4 5 6 7 8 9 10
num x = 0;
cout << "Press 1 to break or 2 to continue ";
while (!(cin >> x))
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Press 1 to break or 2 to continue ";
}