//-----------------------------------------------------------------------------
//                        UU comp., bit parity, Dec/Hex ..
//                                   Dvorka
//                                    1996
//-----------------------------------------------------------------------------

#include "bit.h"

typedef unsigned char byte;
typedef unsigned int  word;
typedef unsigned long dword;

static union { word   w; struct x { byte lo:8; byte hi:8; }b;} Wrd;
static byte *tab,
            invtab[256],               // initialized by InitTab();
            hex[]={'0','1','2','3','4','5','6','7',
                   '8','9','A','B','C','D','E','F'};

word ByteToHex( byte in )
{ Wrd.b.lo=hex[in>>4];Wrd.b.hi=hex[in&0xF];return (Wrd.w); }


byte HexToByte( word in )
{
 return (((in&0x00FF)>'9'? ((in&0x00FF)-'A'+10)<<4: ((in&0x00FF)-'0')<<4)|
         ((in&0xFF00)>'9'<<8? (in>>8)-'A'+10 :(in>>8)-'0'));
}


dword dw3Todw4( dword in )
{
 return ( (in&0x700ul)>>4|(in&0x3F800ul)>>3|
          (in&0x1FC0000ul)>>2|(in&0xFE000000ul)>>1 );
}


dword dw4Todw3( dword in )
{
 return ((in&0x7F000000ul)<<1|(in&0x7F0000ul)<<2|(in&0x7F00)<<3|(in&0x70)<<4);
}


void InitTab( byte *ntab )
{
 byte i; tab=ntab; for( i=0; i<=63; i++ ) invtab[tab[i]]=i; // create inv. tab
}


dword dw3Tabdw4( dword in )
{

 dword i=(in&0xFC000000ul)>>2|(in&0x03F00000ul)>>4|
         (in&0x000FC000ul)>>6|(in&0x00003F00ul)>>8;
       in=tab[*(((char*)&i)+3)]<<8 | tab[*(((char*)&i)+2)];
       in<<=16;
 return ( in | tab[*(((char*)&i)+1)]<<8 | tab[*((char*)&i)] );
}


dword dw4Tabdw3( dword in )
{
 dword i=invtab[(in&0xFF000000ul)>>24]<<8 | invtab[(in&0xFF0000ul)>>16] ;
       i<<=16;
       i|=invtab[(in&0xFF00)>>8]<<8 | invtab[in&0xFF];
 return ( (i&0x3F000000ul)<<2 | (i&0x003F0000ul)<<4 |
          (i&0x00003F00ul)<<6 | (i&0x0000003Ful)<<8 );
}