Pedagani posted:
unsigned int Byte2Int(char *buff)
{
unsigned char* byte = reinterpret_cast<unsigned char*(buff);
return ((byte[0]<<24)|(byte[1]<<16)|(byte[2]<<8)|(byte[3]));
}
Ever heard of const?
I've only written the following code in the last half hour, so it is by no
means perfect. I've checked over it, but not thoroughly, so it may still
contain bugs. Feel free to scrutanise:
#include <climits>
#include <limits>
/* Amalg
-----
Amalgamates an array of "char unsigned" into
a different unsigned integer type.
The boolean template parameter, "MSB_first",
should be "true" if the first array element
is the MSB, otherwise it should be false if
the LSB comes first.
If the quantity of value representation bits in
the unsigned integer type is not a multiple of
CHAR_BIT, then the extraneous bits are retrieved
from the last byte in the array. For example,
if CHAR_BIT were to be 8, and if an "unsigned"
were to consist of 30 value representation bits,
then the array must consist of at least four bytes.
Any remaining bits (6 in this example) will be
retrieved from the fourth "char unsigned".
The quantity of value representation bits does not
include the sign bit, and this algorithm does
not produce the desired result when used with
signed integer types. Nonetheless, the behaviour
is well-defined if used with signed integer types.
Undefined behaviour if "p" does not point to
an array of sufficient length.
*/
template<bool MSB_first, class T>
T Amalg(char unsigned const *p)
{
typedef std::numeric_limits<TI;
/* The following line should optimise away */
if(MSB_first) p += I::digits / CHAR_BIT + !!(I::digits % CHAR_BIT);
T val(MSB_first ? *p-- : *p++);
for(unsigned shift_by = CHAR_BIT;
shift_by < T(I::digits);
shift_by += CHAR_BIT)
val |= T(MSB_first ? *p-- : *p++) << shift_by;
/* 1st cast: Suppress warning for
signed/unsigned comparison. */
/* 2nd cast: In case "char unsigned"
promotes to "int" rather than
"unsigned". */
return val;
}
template<bool MSB_first, class T>
inline T Amalg(char const *const p)
{
return Amalg<MSB_first,T>(p);
}
--
Frederick Gotham