/*
 *   NVRAM WakeUp
 *   Copyright (C) 2001-2002, Sergei Haller.
 *
 *   $Id: byteops.c 381 2003-03-18 13:44:07Z bistr-o-math $
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#define CVSREV_byteops_c \
     "$Id: byteops.c 381 2003-03-18 13:44:07Z bistr-o-math $"

#include "nvram-wakeup.h"

/*
 *  computes the so called BCD notation of an unsigned char,
 *  e.g. the bcd notation of 34 is 0x34 
 *
 *  We don't check, if the conversion makes sense, i.e.
 *  bin2bcd(112) would return 
 *     (112/10) << 4 + 112 % 10 =
 *        11    << 4 +    2     =
 *             0xB0  +    2     = 0xB2
 */
unsigned char bin2bcd( const unsigned char c ) {
     return ((c / 10) << 4)  + (c % 10);
}

/*
 *  computes the unsigned char from its so called BCD notation,
 *  e.g. from 0x34 to 34.
 *
 *  We don't check, if the conversion makes sense, i.e.
 *  bcd2bin(0xAC) would return 
 *     (0xAC >> 4)*10 + 0xAC & 0x0F = 
 *          0xA   *10 +     0xC     =
 *              100   +     12      = 112
 */
unsigned char bcd2bin( const unsigned char c ) {
     return (c >> 4)*10 + (c & 0x0F);
}

/*
 *  this function returns the byte stored in the bits 
 *              sh+nr,..,sh+1 
 *  of byte b, e.g.
 *     b=01011101, sh=0, nr=3
 *            ^^^ --> 101 --> 5 (decimal)
 */
unsigned char calculate_read( const unsigned char b, 
                              const unsigned char nr, 
                              const unsigned char sh) {
     unsigned char msk = 255 >> (8-nr) << sh;
     return (msk & b) >> sh;
}

/*
 *  this function returns the byte calculated by setting the bits 
 *              sh+nr,..,sh+1 
 *  of byte b to the bits nr,..,1 of new, e.g.
 *     b=01011101, sh=2, nr=4, new=00000101
 *         ^^^^  will be set to 0101:  ^^^^
 *  -->  01010101
 *  WARNING: we do not check if new <= 2^(nr-1)
 */
unsigned char calculate_write( const unsigned char b, 
                               const unsigned char _new, 
                               const unsigned char nr, 
                               const unsigned char sh) {
     unsigned char msk = 255 >> (8-nr) << sh;
     return (b & ~msk) | (_new << sh);;
}
