1. ## Hexidecimal printf puzzle

I am on a 6 month internship, before going to Uni. At the moment I am just converting all my visual basic skills to C programming, and during my training, I came across something I have spent hours to work out. It is not urgent, or really needed, but if you can explain it, it would be very helpful. It has completely thrown 2 people who work here, proffesionally in C.

Code:
```include "stdio.h"
#include "stdlib.h"
#define MAX_DIGITS 16

main ()
{

/* Set up */

static char word[MAX_DIGITS] =  { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,};
int i;
int j;
int temp;
int shiftw;

/* Print table */

for (i = 0; i < MAX_DIGITS; i++)
{
printf("&#37;x, ", word[i]);
}
printf("\n");

/* Nibbilise it */

/* Original code, if you are interested
*  for (i = 0,j=0; j < MAX_DIGITS/2 -1; i=i+2,j++)
*  {
*      word[j] = ((word[i] << 4) & 0xf0) | (word[i + 1] & 0x0f);
*  }
*/

/* Will do for demonstration */
for (i=0; i< MAX_DIGITS; i++)
{
word[i] = word[i]<<4;
}

/* Print New */

for (i = 0; i < MAX_DIGITS; i++)
{
printf("%x, ", word[i]);
}
printf("\n");
}```
The program was meant to shift each single hex digit across so that 1,2,3,4,5,6,7... would become 12,34,56,7... and only take up half the array.

I had been using scanf to fill word[], reading them in as hex values, but I took this out so you can see my problem.

Output:
Code:
```0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f,
0, 10, 20, 30, 40, 50, 60, 70, ffffff80, ffffff90, ffffffa0, ffffffb0, ffffffc0, ffffffd0, ffffffe0, fffffff0,```
We cant work out why it prints any shifted hex value between 8 and f, by putting 6 f's infront. Is it a 2's compliment problem? The gbd tool says it stores the value correctly, so why does printf do this? I think it is some way the printf works, but I cant seem to find an answer anywhere.

2. ## Hoho

try redefine the "word" "static char" to "static unsigned char"!

u will find the result is what u want!

3. Thanks. Forgot about declaring it unsigned. Still a little new to this. However, can you explain why gdb stated that it was storing it correctly, and printf printed it otherwise? is it something gdb does, or printf. If I understand the problem, I can avoid it better.

4. Yes it's stored correctly. Your shifts, or, masks etc. all look fine.
You could also try
Code:
`printf("&#37;x, ", (unsigned char)word[i]);`
The problem occurs when the argument to printf() is automatically promoted from char to int. Because the char is negative in some cases (high bit is set), the conversion sets all high order bits in the integer to 1 as well. Hence it comes out as ffff... You can review how negative numbers are represented.

5. I like how the supposedly professional C programmers could not solve this problem.