Question About Casting

D

David Vestal

I'm reading a 24-bit address from a char* named i_msg, and I expected these
two snippets to be equivalent. They aren't; the first doesn't work. What
gives?

SNIPPET 1:

unsigned long address;
address = ((unsigned long) i_msg[2]) << 16
+ ((unsigned short) i_msg[3]) << 8
+ i_msg[4];

SNIPPET 2:

unsigned long address;
address = i_msg[2];
address <<= 8;
address += i_msg[3];
address <<= 8;
address += i_msg[4];
 
T

Thomas Stegen

David said:
I'm reading a 24-bit address from a char* named i_msg, and I expected these
two snippets to be equivalent. They aren't; the first doesn't work. What
gives?

SNIPPET 1:

unsigned long address;
address = ((unsigned long) i_msg[2]) << 16
+ ((unsigned short) i_msg[3]) << 8
+ i_msg[4];

The addition is done before the shifting.
 
D

David Vestal

David said:
I'm reading a 24-bit address from a char* named i_msg, and I expected
these two snippets to be equivalent. They aren't; the first doesn't
work. What gives?

SNIPPET 1:

unsigned long address;
address = ((unsigned long) i_msg[2]) << 16
+ ((unsigned short) i_msg[3]) << 8
+ i_msg[4];

The addition is done before the shifting.

*groan* Thanks. I'm too old to be making mistakes like that.
 
D

Dan Pop

In said:
I'm reading a 24-bit address from a char* named i_msg, and I expected these
two snippets to be equivalent. They aren't; the first doesn't work. What
gives?

You have to throw more parentheses at the problem: the compiler is
blissfully ignoring your nice formatting of the expression and uses the
C precedence rules instead ;-)
SNIPPET 1:

unsigned long address;
address = ((unsigned long) i_msg[2]) << 16
+ ((unsigned short) i_msg[3]) << 8
+ i_msg[4];

This is interpreted as:

(((unsigned long) i_msg[2]) << (16 + ((unsigned short) i_msg[3]))) <<
(8 + i_msg[4])

which probably not what you want. Try the following instead:

address = (((unsigned long) i_msg[2]) << 16)
+ (((unsigned short) i_msg[3]) << 8)
+ (unsigned char) i_msg[4];

Note that, unless plain char is unsigned, the last cast I have added is
needed, too.

Dan
 
M

Mark A. Odell

I'm reading a 24-bit address from a char* named i_msg, and I expected
these two snippets to be equivalent. They aren't; the first doesn't
work. What gives?

SNIPPET 1:

unsigned long address;
address = ((unsigned long) i_msg[2]) << 16
+ ((unsigned short) i_msg[3]) << 8
+ i_msg[4];

The addition is done before the shifting.

*groan* Thanks. I'm too old to be making mistakes like that.

Using | instead of + would have worked. Were you thinking of that?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top