Cryptography Reference
In-Depth Information
C++ standard library contain member functions that permit the setting of objects
into an input or output stream for file operations, so we are fortunate in that we
can use the same syntax as we used above. The operators needed for output to
files are similar to those of the last section, where, however, we can do without the
formatting.
We define the two operators
friend ofstream& operator<< (ofstream& s, const LINT& ln);
friend fstream& operator<< (fstream& s, const LINT& ln);
for output streams of the class
ofstream
and for streams of the class
fstream
,
which supports both directions, that is, both input and output. Since the class
ofstream
is derived from the class
ostream
, we can use its member function
ostream::write()
to write unformatted data to a file. Since only the digits of
a
LINT
object that are actually used are stored, we can deal sparingly with the
storage space of the data medium. Here the
USHORT
digits of the
LINT
object are
actually written as a sequence of
UCHAR
values. To ensure that this always occurs
in the correct order, independent of the numerical representation scheme of a
particular platform, an auxiliary function is defined that writes a
USHORT
value as
a sequence of two
UCHAR
types. This function neutralizes the platform-specific
ordering of the digits to base 256 in memory and thereby allows data that were
written on one computer type to be read on another that possibly orders the digits
of a number differently or perhaps interprets them differently when they are read
from mass storage. Relevant examples in this connection are the
little-endian
and
big-endian
architectures of various processors, which in the former case order
consecutive increasing memory addresses in increasing order, and in the latter
case do so in decreasing order.
2
template <class T>
int write_ind_ushort (T& s, clint src)
{
UCHAR buff[sizeof(clint)];
unsigned i, j;
for(i=0,j=0;i<sizeof(clint); i++,j=i<<3)
{
buff[i] = (UCHAR)((src & (0xff << j)) >> j);
}
s.write (buff, sizeof(clint));
2
Two bytes
B
i
and
B
i
+1
with addresses
i
and
i
+1
are interpreted in the little-endian rep-
resentation as
USHORT
value
w
=2
8
B
i
+1
+
B
i
and in the big-endian representation as
w
=2
8
B
i
+
B
i
+1
. The analogous situation holds for the interpretation of
ULONG
values.