I need to save ant interger with values ranging from 0-65535 (0-FFFF) to a
string and later retrieve the value.
For example:
..
int i;
char mytxt[2];
i=55;
..
What would be the fastest way to save i to mytxt and later retrieve it? I am
looking from a simple cast if possible. I want to avoid using fuction calls.
Nomenclature: What you describe is not a "string" as C uses
the term. In C, a "string" is an array of `char' containing zero
or more non-zero "payload" characters followed by one zero byte
to mark the end. You've got an array of `char', but it's not a
"string" unless by coincidence.
Moving on: The first thing you should do is change `char' to
`unsigned char', avoiding potential mysteries on systems where
`char' is a signed type. An `unsigned char' can hold values from
0 through 255 (possibly higher, but that's rare), but a plain
`char' might go only as high as 127. And then:
int i = ... something between 0 and 65535 ...
unsigned char mybytes[2]; // `mytxt' is a misleading name
mybytes[0] = i & 0xff;
mybytes[1] = i >> 8;
...
int j = (mybytes[1] << 8) + mybytes[0];
(You could reverse the positions of the low- and high-order bytes,
if you like, so long as the encoding and decoding use the same
convention.)
There are no guarantees about speed, but one approach that
is likely to be faster is
int i = ... something between 0 and 65535 ...
unsigned short mybytes;
mybytes = i;
...
int j = mybytes;
Whether you can use this depends on whether you truly need a
two-character array; you haven't explained that requirement.