
convert char to short int via pointer?...
|> I got the following problem:
|>
|> unsigned char * ptr;
|> short int value;
|>
|> ptr = ...; /* Points to an array of raw data. */
|>
|> value = (short int)*ptr;
^^^^^^^^^^^^^^^
I'm not sure what you're trying to do here. Essentially, this
assignment takes the unsigned char value of ptr[0] and assigns
it to value. I don't think this is what you intended.
|> Value is supposed to contain a short int constructed from *ptr
|> plus *ptr+1 in signed little endian format.
It sounds as if what you're intending to do is something like
unsigned char data[] = { BYTE1, BYTE2 };
ptr = data;
value = *(short *)ptr;
That is, take the unsigned char pointer value, cast it to a pointer
to short int, and then dereference, placing the result in value.
|> Does this work? And if not, how could it work?
It might work, but it's very unsafe. Perhaps the worst problem
with this approach is alignment. In C, pointers to char (and
equivalently, pointers to void) have the least-strict alignment
requirements; as a result, ptr may be properly aligned for access
to unsigned char, but it may *not* be aligned for access to a
short int. (In this case, the cast will result in undefined
behavior; a common result of this is a "bus error".)
A safer way to do what you're trying to accomplish is to use
the memcpy() function to physically copy the contents of the "raw
data" to the short object:
memcpy(&value, ptr, sizeof(short));
(Remember to #include <string.h>.)
It is both unsafe and unportable to assume that ptr is properly
aligned to access objects of type short. By copying the value
(instead of "interpreting" it, as it were) you remove any danger
due to alignment considerations.
Regards,
--
Chris Engebretson - Raytheon STX Corporation | Ph#: (605)594-6829
USGS EROS Data Center, Sioux Falls, SD 57198 | Fax: (605)594-6940
Opinions are not those of Raytheon Systems Company or the USGS.