Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Answer to a practice interview question

I'm just going through a bunch of C++ interview questions just to make sure there's nothing obvious that I don't know. So far I haven't found anything that I didn't know already, except this:

long value;
//some stuff
value &= 0xFFFF;

The question is "what's wrong with this code?" And hints that it's something to do with target architectures.

Unless the answer is just "value isn't initialized", I can't see any problem. As far as I can tell, it's just masking the 2 least significant bytes of the value, and long is guaranteed to be at least 2 bytes, so there's no problem there.

Could it possibly be that long might only be 2 bytes on the target architecture, and you might be losing the sign bit? Or perhaps that the 0xFFFF is an int and int is only 2 bytes?

Thanks in advance.

like image 762
Peter Alexander Avatar asked Mar 01 '10 22:03

Peter Alexander


People also ask

How do you answer a mock interview?

To answer the question, explain how your knowledge and skills are well-suited to what they're looking for. You can also say something about your career aspirations and share how you can contribute to achieving the company's goals.


1 Answers

This problem with this code is that it does a bit-wise operation on a signed value. The results of such operations on negative values vary greatly for different integer representations.

For example consider the following program:

#include <iostream>

int main(void)
{
    long value;
    value = -1; // Some stuff
    value &= 0xffff;
    std::cout << "Value = " << value << std::endl;
}

On a two's-complement architecture the result is:

Value = 65535

On a one's-complement architecture the result is:

Value = 65534

On a sign-and-magnitude architecture the result is:

Value = 1
like image 155
Dingo Avatar answered Nov 15 '22 21:11

Dingo