/*
 * ul_bcd.h
 *
 *  Created on: Sep 11, 2011
 *      Author: qwer1
 */

#ifndef UL_BCD_H_
#define UL_BCD_H_

#include "ul_other.h"

extern U8 asc_point;
extern U8 asc_space;
extern U8 asc_minus;

/** convert lower nibble to HEX symbol */
#define to_hex(bbb) (((bbb) & 0xF) > 9 ? ((bbb) & 0xF) + ('a' - 10) : ((bbb) & 0xF) + '0')

/** 8-bit BCD->BIN conversion */
U8 bcd2bin_U8( U8 bcd );
/** 8-bit BIN->BCD conversion */
U8 bin2bcd_U8( U8 bin );

/** 32-bit BIN->BCD conversion
 *  data - input word,
 *  result_bytes - max.number of result bytes.
 */
U32 bin2bcd_U32_soft(U32 data, U8 result_bytes);

/** 32-bit BCD->BIN conversion
 *  data - input word,
 *  input_bytes - max.number of input bytes.
 */
U32 bcd2bin_U32_soft(U32 data, U8 input_bytes);

// AVR-optimized conversions
#ifdef __AVR__
    U32 bin2bcd_U32_avr(U32 data, U8 result_bytes);
    U32 bcd2bin_U32_avr(U32 data, U8 input_bytes);
#endif

/** convert 32-bit signed data to ASCII number to buffer (right to left)
 * options & 7 - width-1,
 * (options >> 4) & 7 - point position,
 * options & 0x08 - supress leading zeros,
 * options & 0x80 - convert to BCD.
 */
#define NUM2ASC_BCD     (U8)0x80
#define NUM2ASC_NOZEROS (U8)0x08
#define NUM2ASC_FLAGS( w, p, bcd, nozeros) (U8)( (((U8)w-1)&7) + ((U8)p<<4) + (bcd * NUM2ASC_BCD) + (nozeros * NUM2ASC_NOZEROS) )
#define NUM2ASC_S32( data, buf, w, p, bcd, nozeros ) num2asc_S32( data, buf, NUM2ASC_FLAGS( w, p, bcd, nozeros ))
void num2asc_S32(S32 data, U8 *buf, U8 options);

#endif /* UL_BCD_H_ */
