In c++ an int consists of 4 bytes and can hold a max value of 2147483647 (2^31-1). Should you ever feel the obscure need to merge two ints, because you know that both of your values will never be blow 0 or above 32767 (2^15-1) use the following methods.
1) Merging
1 2 3 4 | int mergeTwoInts(const int first, const int second) { return (first << 16) | second; } |
2) Splitting
1 2 3 4 5 6 7 | int *splitToTwoInts(const unsigned int merged) { int *ret = new int[2]; ret[0] = (merged << 16) & 0xFFFF; ret[1] = merged & 0xFFFF; return ret; } |
3) applying in a test method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | int _tmain(int argc, _TCHAR* argv[]) { int id = 65533; int id2 = 65531; // merge ints unsigned int merged = mergeTwoInts(id, id2); cout << id << endl; cout << id2 << endl; cout << merged << endl; // split ints int* splitInts = splitToTwoInts(merged); cout << splitInts[0] << endl; cout << splitInts[1] << endl; cout << merged << endl; system("pause"); return 0; } |
Conclusion:
c++ empoweres me to do probably unnecessary and weird stuff.
December 5, 2014 at 9:03 am
i think there’s an error in your code, and when you split it should be a right shift