0

For example:

short a = 10;
int b = a & 0xffff;

Similarly if I want to convert from int to short, how do I do using bitwise operators? I don't want to use the usual casting using (short).

IS4
  • 11,945
  • 2
  • 47
  • 86
Souvik Das
  • 33
  • 7

3 Answers3

2

If you want sign extension:

int b = a;

If you don't (i.e. negative values of a will yield (weird) positive values of b)

// note that Standard Conversion of shorts to int happens before &
int b = a & std::numeric_limits<unsigned short>::max();
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
1

Doing bit-operations on signed types may not be a good idea and lead to surprising results: Are the results of bitwise operations on signed integers defined?. Why do you need bit-operations?

short int2short(int x) {
    if (x > std::numeric_limits<short>::max()) {
        // what to do now? Throw exception, return default value ...
    }
    else if (x < std::numeric_limits<short>::min()) {
        // what to do now? Throw exception, return default value ...
    } else
    {
        return static_cast<short>(x);
    }
} 

This could generalized into a template method and also have policies for the error cases.

Community
  • 1
  • 1
Jens
  • 9,058
  • 2
  • 26
  • 43
0

Why not using (short)? That's the easiest way and gets what you want.

Unless it's an interview problem, then you need to assume how many bits a short and a int contains. If the number is positive, just using bitwise AND. If the number is negative, flip it to positive number, and do bitwise AND. After AND, you need to change the highest bit to 1.

shao
  • 31
  • 3