Bart <bc@freeuk.comwrites:
On Aug 12, 9:44*am, ssubbarayan <ssu...@gmail.comwrote:
[...]
>I was expecting it to print 2007.But due to wrong byte swapping,it was
showing 55047 instead of 2007.
The idea behind asking this question is,I have got stream of data in
different data types and already an existing function recieves it and
parses it by bytes.
In this particular case you might know the year must be, say, 1900 to
2100. Any byte swapping will give year values outside this range
(except for year 2056 which is unaffected). In that case just reverse
the two bytes when the year is not already 1900 to 2100.
Sure, that will work in this particular case, but it's not a great
technique in general. Tomorrow you might have to handle data values
that are still plausible after being byte-swapped.
A more general approach is either to know in advance what the byte
ordering of the input file happens to be, or, if that's not feasible,
to have something in the file with a known value that will
unambigously tell you the byte ordering.
For example, a file might contain fixed fields containing the values
0x0102 (16 bits) and 0x01020304 (32 bits). Examining the values of
those fields should tell you what adjustments you need to perform for
other 16-bit and 32-bit fields.
Note that there are byte orderings others than big-endian and
little-endian. For a 32-bit value, 0x02010403 is a possibility on
some systems (but not on any systems you're particularly likely to
encounter).
For reasonable portability, the only values you probably need to worry
about are (0x0102, 0x01020304) and (0x0201, 0x04030201), as long as
you treat any other values as an error.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"