Geting/Setting individual Bytes (octets)

The library provides two (x2) functions for getting and setting individual bytes [1] in an unsigned_int<>, also (in namespace imp::adl) are two generic function's for getting bytes from other (inbuilt) unsigned types.

Tests

get_byte()

unsigned char get_byte( unsigned_int< ... > const &, unsigned offset );

unsigned_int< 16 * 8 > a( "0xFFEEDDCCBBAA99887766554433221100" );

for ( unsigned i = 0; i < 16; ++i )
{
  unsigned char b = get_byte( a, i );
  CHECK( b == ( i | (i << 4 ) ) );
  std::cout << std::hex << std::setw(2) << std::setfill( '0' ) << unsigned( b );
}
std::cout << std::endl;

Test Result: gcc34 Passed, msvc80 Passed, msvc71 Passed

Output

00112233445566778899aabbccddeeff
Ok

get_byte() - inbuilt

template < Int > unsigned char get_byte( Int const &, unsigned offset );

unsigned long a( 0x33221100L );

for ( unsigned i = 0; i < 4; ++i )
{
  /* ADL cant find *inbuilts*
  */
  using namespace imp::adl;
  
  unsigned char b = get_byte( a, i );
  CHECK( b == ( i | (i << 4 ) ) );
  std::cout << std::hex << std::setw(2) << std::setfill( '0' ) << unsigned( b );
}
std::cout << std::endl;

Test Result: gcc34 Passed, msvc80 Passed, msvc71 Passed

Output

00112233
Ok

set_byte()

unsigned_int< ... > &set_byte( unsigned_int< ... > &, usigned offset, unsigned char value );

unsigned_int< 16 * 8 > a( "0xFFEEDDCCBBAA99887766554433221100" ), b;

for ( unsigned i = 0; i < 16; ++i )
{
  set_byte( b, i, get_byte( a, i ) );
}
CHECK( a == b );
std::cout << std::hex << b << std::endl;

Test Result: gcc34 Passed, msvc80 Passed, msvc71 Passed

Output

ffeeddccbbaa99887766554433221100
Ok

set_byte() - inbuilt

template < Int > Int &set_byte( Int &, unsigned offset, unsigned char value );

unsigned long a( 0x33221100L ), b = 0;

for ( unsigned i = 0; i < 4; ++i )
{
  /* ADL cant find *inbuilts*
  */
  using namespace imp::adl;
  
  set_byte( b, i, get_byte( a, i ) );
}
CHECK( a == b );
std::cout << std::hex << b << std::endl;

Test Result: gcc34 Passed, msvc80 Passed, msvc71 Passed

Output

33221100
Ok
[1]

Byte here means octet:

i.e. a unsigned value with exactly 8 bits of storage.

In C++ (and C) byte means the minimum unit of storage an implementation supports, usually this is 8 bits but 16 or 32 bits aren't uncommon and 9, 18 and 36 have been used (also 12 If I remember correctly).