The following lines of code output "FFFFFFFF"

#include <stdio.h>

int main(void)
{
int i;
i=-1;
printf("\n%X\n",i);
return 0;
}

This is the 32-bit representation of -1 in Hex. I'm trying to get it to output fewer bits: e.g. 24-bit: FFFFFF In fact, the output I want needs to be 6 digits in all cases. So, if I replaced i=-1 with i=1 I need the output to be 000001. I can do this by padding with 0's

(i.e., use printf("\n%06X\n",i);)

but the negative case still outputs FFFFFFFF. I vaguely understand why this is happening, but not sure the easiest way to fix. I could convert the output to a string, and chop off the first two characters, but this seems a bit convoluted. Any suggestions?

You could try a union with a packed structure..If you using MS you'll have to Google to find out how to pack a structure...

#include <stdio.h>

union mu
{
	int x;
	struct
	{
		unsigned int a:8;
		unsigned int b:24;
	}__attribute__((packed)) in;
};

int main(void)
{
	union mu theu;
	theu.x = -1;

	fprintf(stdout, "%x\n", theu.in.b);
	return 0;
}

Output

ffffff

That sounds even more convoluted.
You could clear out the bits you don't want: i = i & 0xFFFFFF; to make the value 24 bits.

That sounds even more convoluted.
You could clear out the bits you don't want: i = i & 0xFFFFFF; to make the value 24 bits.

I'm not trying to start an argument but your solution still has the original amount of bits, its not 24 bits but 32 bits with a masking operation..Maybe I misunderstood the op?

As the OP said,

I'm trying to get it to output fewer bits: e.g. 24-bit: FFFFFF In fact, the output I want needs to be 6 digits in all cases.

Clearing out the top 8 bits effectively gives you a 24 bit value. Therefore, 6 digits can be output.

For example, try this:

#include <stdio.h>
int main()
{
    int i=-1;

    for (i=5; i > -5; i--)    
        printf("%06X\n", i & 0xFFFFFF);
    
    return 0;
}

WaltP I don't disagree with your reasoning, I'm just stating that the variable is still sizeof(int) in size...Its probably cutting hairs but that's just the way I am..

Every integer you pass to printf is sizeof(int) in size, unless it promotes bigger -- you can't pass anything smaller. The only way to print a 24 bit object is to write your own routine with putchar().

OTOH, you could use 3 chars.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.