# -*- coding: utf-8 -*-
# Numeric conversions
#
# Copyright (C) 2011 Michal Kajan, Libor Polčák, Petr Kramoliš
# 
# 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

"""
This module collects functions and classes related to processing of numbers and
their conversions.
"""

def inttoNbytes(integer, bytes_count):
    """ Converts given integer to given-number-of-bytes-long bytes """
    varlen_hexstr = hex(integer)[2:][-2*bytes_count:]
    zeroes = bytes_count*2 - len(varlen_hexstr)
    hexstr = ("0" * zeroes) + varlen_hexstr
    hexdigits = [hexstr[(b*2):(b*2+2)] for b in reversed(range(bytes_count))]
    return bytes([int(d, 16) for d in hexdigits])

def intfromNbytes(field, bytes_count):
    """ Converts given-number-of-bytes-long bytes to integer """
    if bytes_count == 1:
        return field # bytes unit is the integer itself
    res = 0
    for i in reversed(range(bytes_count)):
        res += field[i]*(256**i)
    return res

