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("%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.