2 chars to signed short

I have two char values char_1 and char_2. Now I want to combine them to an 16 Bit signed integer value where char_1 contains the sign in the MSB.

|SGN|Bit 6|Bit 5|Bit 4|Bit 3|Bit 2|Bit 1|Bit 0|Bit 7|Bit 6|Bit 5|Bit 4|Bit 3|Bit 2|Bit 1|Bit 0|

| Sign Char 1 | Rest of Char 1 | Char 2 |

My try was:

signed short s = (((int)char_1) << 8) & (int)char_2;

Now I get 0 for s...

Answers


You need a bitwise or not and

(((int)char_1) << 8) | (int)char_2;

Since you're also dealing with bits, you should probably use unsigned types too (unsigned char, unsigned int, unsigned short.)


A cleaner solution might be achieved by Unions.

typedef union { short int s; char c[2];} Data;

int main (){
        Data d;
        d.c[0]=char_2;
        d.c[1]=char_1;
}

Note: This may not be portable enough for you as the order of the indexes depends on architecture endianness. My example works well on Little endian archs (ie Intel 0x86) but big endian archs would print char_2 char_1.


Need Your Help

Setting up Tower 2 with Git Two Factor Authentication

github two-factor-authentication git-tower

I have turned on my github's two factor authentication. I am able to push and pull from the terminal but not able to do it via Tower. I am able to see all my branches in tower, but not able to push...