Dave Coventry
Dave Coventry

Reputation: 141

Unsigned int not giving expected value

I'm reading 2 bytes from a file and trying to use the unsigned int as an ID for my SVG output.

unsigned int character_name_1;
unsigned int character_name_2;

fread( buffer, sizeof( char ), 4, fpi );
character_name_1=(((buffer[1]<<8)+buffer[0])&0xFFFF);
character_name_2=(((buffer[3]<<8)+buffer[2])&0xFFFF);

If the file has 2 values 126 and 128 which are 0x007E and 0x0080 (buffer[0]=0x7E and buffer[1]=0x00), then, if I print out to my SVG file <g id=%u d=%s></g>",character_name_1, pathdata);, then I get the id correctly recorded as 'id="126"'.

However, the second value is problematic:<g id=%u d=%s></g>",character_name_2, pathdata); gives me the following entry: 'id="65408"'

The next value, which has the 2 bytes 0xA0 and 0x00, which I am expecting to be 160 is written as 65440. 0xA1 and 0x00 should be 161, but I'm getting 65441.

I hope this is clear.

Upvotes: 0

Views: 159

Answers (3)

Yaniv Shaked
Yaniv Shaked

Reputation: 758

Your definition of buffer is probably a signed type (char).

This causes the value 0xA1 to be interepeted as a negative number and automatic sign extension is invoked (0xA1 -> 0xFFA1), to make sure the sum (buffer[3]<<8 + buffer[2]) is handled correctly. So you get the value of 0xFFA1, which is 65441.

Changing buffer to unsigned char will solve your issue.

Upvotes: 2

Cool Goose
Cool Goose

Reputation: 998

Not much clear from your question, assuming buffer is array of character or character pointer. I think following change should work:

character_name_1=(((buffer[1]<<8)+buffer[0])&0xFF);
character_name_2=(((buffer[3]<<8)+buffer[2])&0xFF);

Upvotes: -1

Eric Postpischil
Eric Postpischil

Reputation: 222273

buffer is declared with char or signed char. Change it to unsigned char.

Because the elements in your buffer are signed, you are getting negative values in your expressions.

Upvotes: 1

Related Questions