I'm trying the following code to combine ints, and then get the original ints back:

#include <iostream>

using namespace std;

int getleft(int n){
	return (n >> 24);
}

int getright(int n){
	return ((n << 8) >> 8);
}

int main(){
	int i = 15;
	int j = 28515;
	int combined = i << 8 | j;
	cout << getleft(combined) << endl;
	cout << getright(combined) << endl;
}

But it doesn't work; getright() works and gives 28515, but getleft() gives 0.

What's my mistake?

28515 is bigger then 2^8 (=256) So only shifting 8 bits is not enough.

so the max number you can add would be half an integer = 65535, but you would have to shift 16 bits, because (normally) an integer is 32 bits:

int main(){
    /*max 65535 (= sizeof(unsigned int) /2) */
    unsigned int i = 2222; 
    unsigned int j = 1111;
    unsigned int combined = (i << 16) | j;
    cout << (combined >> 16) << endl;
    cout << ((combined << 16) >> 16);
}

In addition to what niek_e sead, you could make things easier by using some windows macros.

#include<windows.h>
#include<iostream>
using namespace std;

int main(){
    /*max 65535 (= sizeof(unsigned int) /2) */
    unsigned int i = 2222; 
    unsigned int j = 1111;
    unsigned int combined = MAKELONG(i, j);
    cout << LOWORD(combined) << '\n';
    cout << HIWORD(combined);
    cin.ignore();
    return 0;
}

Thank you, I realized my mistake - I had been doing:

int combined = i << 8 | j;

Instead of:

int combined = i << 24 | j;

williamhemswort, I am using Linux :)

A related question - for int, is it the leftmost bit that holds the sign? And is it 0 for positive, 1 for negative, or the other way around?

A related question - for int, is it the leftmost bit that holds the sign? And is it 0 for positive, 1 for negative, or the other way around?

Correct, 1 for negative. See http://en.wikipedia.org/wiki/Twos_complement for how it's done

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.