last day (14 days later) » 

4:18 PM
1
A: Convert MSB first to LSB first

RedRoboHoodHere's a simple but slow implementation: #include <cstdint> const size_t USHORT_BIT = CHAR_BIT * sizeof(unsigned short); unsigned short ConvertMsbFirstToLsbFirst(const unsigned short input) { unsigned short output = 0; for (size_t offset = 0; offset < USHORT_BIT; ++offset) { output |= ...

 
USHORT_BIT is good for the usual situation where unsigned short has no padding bits. Should unsigned short have padding, a different USHORT_BIT calculation is needed.
 
In what situations would you say that unsigned short is padded?
 
The spec detail "For unsigned integer types other than unsigned char, the bits of the object representation shall be divided into two groups: value bits and padding bits (there need not be any of the latter)." In a system that has no native short type implemented in hardware, padding of a wider type can be used to implement the short. Still - your bit conversion code is on the right track +1.
 
@chux So is it possible for an unsigned short to have a number of value bits other than 16?
 
Certainly unsigned short can be > 16 bits. Still 16 is the most common. It must at least cover the range of 0 to 65535. Should code need exact 16 bits, use uint16_t. BTW: "possible for an unsigned short to have a number of value bits other than 16?" is a good post-able question.
 
4:18 PM
@chux In the case that the number of bits in an unsigned short is greater than 16, is there a way to determine which of the bits are value bits and which of the bits are padding bits?
Oh, cool, I didn't know you could do that.
Wait, how do you do that?
 
The usual approach is to ignore the size and use USHRT_MAX.
 
So, take the logarithm of that number?
 
Maybe as simple as #if USHRT_MAX == 65535 #define USHORT_BIT 16 #else #error too weird #endif
 
Or constexpr function that calls std::nuke_from_orbit
 
There are some involved compile time approaches to get the width - see if I can find one.
"nuke_from_orbit" LSNED.
 
4:24 PM
It's in the <wmd> header if you're interested.
 
Something like stackoverflow.com/a/27475798/2410359 to do a compile time log2, but likely needs work. The #if USHRT_MAX == 65535 #define USHORT_BIT 16 #elif USHRT_MAX == 4294967295u #define USHORT_BIT 32 #elif USHRT_MAX == some other typical value ... is reasonable too.
 
That would apply to both C and C++, yes, but if C++-only answers were allowed, a constexpr with a simple loop would be clearer.
 
C++ does simply some things. GTG
 

last day (14 days later) »