Data Type Problem unsigned short
I am using data type unsigned short on two functions. An input function and an output function.
for example if users type like
Code:
unsigned short x =100;
unsigned short y;
y = input(x);
y = output(x);
cout<<y;
//the output should be 100
the problem is, the function can only take 2^(15) -1 or 32767. I can't figure out the problem. For instance if your input is over 32767, it gives wrong result.
Here is the code for both function
Code:
unsigned short Input(unsigned short usData)
{
unsigned short usOutputBit = 0;
static int nRegisterBitValue = 0;
unsigned short usResult = 0;
unsigned short usResult2 = 0;
unsigned short usInputBit;
unsigned short usBit;
int i;
usInputBit = usData;
for (i = 0; i < 16; i++)
{
usBit = (usInputBit & 0x8000) ? 1 : 0;
usOutputBit = usBit ^ nRegisterBitValue;
nRegisterBitValue = usOutputBit;
usInputBit = usInputBit << 1;
usResult = (usOutputBit | 0x8000) | usResult2;
usResult = usResult << 1;
usResult2 = usResult;
if(usInputBit == 0)
{
usResult = usResult >> 1;
}
}
return(usResult);
}
unsigned short Output(unsigned short usData)
{
unsigned short usOutputBit = 0;
unsigned short usResult2 = 0;
static int nRegisterValue = 0;
unsigned short usResult = 0;
unsigned short usInputBit;
unsigned short usBit;
int i;
usInputBit = usData;
for (i = 0; i < 16; i++)
{
usBit = (usInputBit & 0x8000) ? 1 : 0;
usOutputBit = usBit ^ nRegisterValue;
nRegisterValue = usBit;
usInputBit = usInputBit << 1;
usResult = (usOutputBit | 0x8000) | usResult2;
usResult = usResult << 1;
usResult2 = usResult;
if(usInputBit == 0)
{
usResult = usResult >> 1;
}
}
return(usResult);
}
I think the problem may be in this line of code
usResult = (usOutputBit | 0x8000) | usResult2;
which I use to pack the bit together