Ikaruga
Ikaruga

Reputation: 61

Bitwise operations on elements from array of chars

I have made array of hexadecimal numbers that I would like to add together bitwise. In my program I want to add 0xFF with 0x7F00. Here is my approach

#include <iostream>

using namespace std;

int main() {

    char data[2] = {0xFF, 0x7F};

    cout << (data[0] | (data[1] << 8)) << endl;

    system("pause");
    return 0;
}

I expect the result to be 0x7FFF which is 32767 in decimal, but I get -1 (0xFF in hex).

Upvotes: 0

Views: 535

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

The problem you're having stems from two facts:

  1. The bitwise operators requires integral promotion of both operands.
  2. char can be either signed or unsigned

Promotion will convert values of smaller types (like char or short) to int, and as part of that signed values will be sign-extended. If char is signed, then the value 0xff will be converted to the (32-bit) int value 0xffffffff, which is -1.

It doesn't matter what value you use in the bitwise OR, the result will still be 0xffffffff.

The simple solution is to explicitly use unsigned char (or even better uint8_t) as the type for the array elements:

uint8_t data[2] = {0xFF, 0x7F};

Upvotes: 2

Related Questions