You have to think about signed or unsigned data.
When you use BCD numbers, i.e. pack digits in nibbles, the most
significant packed nibble will behave differently if the "container"
byte/word is signed or unsigned, since the mist significant bit of the
word is the sign bit.
The digit 8 or 9 are the only BCD values (0..9) that have the most
significant bit set, so they are the only BCD values what would correspond
to a negative value for the "container" word.
Try your program again, but use a unsigned char/unsigned short/unsigned
int/unsigned long... to store the BCD number.
/pwm
On Mon, 16 Jul 2007, Jerome Knapp wrote:
> /*Hi Everybody-
> Im new, wrote this little program to see how I could pack some
> bcd bytes for another project. Im curious why I get "ffffff8 _ when I enter 8
> or 9 for the first or 3rd digit. Can some one explain where this comes
> from? I can get rid of it with
>
> printf ("packed value of digits is %2X \n", (digit[i]& 0x0ff));
>
> but Im curious where it comes from and why only for 8 or 9, must have to do with bit 3.
>
> Thanx
> Mot
> */
> //==================================================
> #include <stdio.h>
> #include <stdlib.h>
> #include <conio.h>
>
> int i,j =0;
> char digit[5];
>
> //this program takes in 4 digits from the keyboard and packs them into 2 packed-bcd bytes.
>
> int main(int argc, char *argv[])
> {
>
> for (i=0;i<4; i++) {// 4 single digits = two packed bcd bytes
> while (!kbhit()); //wait
> digit[i]=getch(); // getch gets the char from the buffer
> printf("%d",digit[i],"\n"); // echo back
> printf(" ascii the value of i is %d\n",i);
> }
>
> //now convert from ascii to hex
> for (i=0;i<4; i++) {// 4 single digits = two packed bcd bytes
> digit[i]=digit[i]-48; //convert from ascii to decimal
> printf("%d",digit[i],"\n"); // echo back
> printf(" the value of i is %d\n\n",i);
> }
>
> //now pack the bcd
> digit[0]= (digit[0]<<4) | (digit[1]);
> digit[1]= (digit[2]<<4) | (digit[3]);
> printf ("digits packed are %x %x \n\n", digit[0],digit[1]);
>
> system("PAUSE");
> return 0;
> }
> //==========================================================
>
>
|