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).

3
  • Related: size of int, long, etc.
    – Drux
    Commented Apr 3, 2014 at 6:20
  • 1
    There is nothing to do here; it's simply int b = a; or short a = b;. Commented Apr 3, 2014 at 6:22
  • 1
    Why don't you want to use a cast?
    – user207421
    Commented Apr 3, 2014 at 6:23

3 Answers 3

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();
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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.