/**
 *	Binary utilities
 */
#Const Version    "2016-12-12"
#Const ScriptName "Libs/Nadeo/Binary.Script.txt"

// ---------------------------------- //
// Libraries
// ---------------------------------- //
#Include "MathLib" as ML

// ---------------------------------- //
// Functions
// ---------------------------------- //
// ---------------------------------- //
/** Convert a positive Integer to a 
 *	binary number
 *
 *	@param	_Int											The positive Integer to convert
 *
 *	@return														The binary number
 */
Integer[] ToBinary(Integer _Int) {
	if (_Int < 0) return Integer[];
	declare RevertBinary = Integer[];
	declare Int = _Int;
	while (Int > 0) {
		RevertBinary.add(Int % 2);
		Int /= 2;
	}
	return RevertBinary;
}

// ---------------------------------- //
/** Convert a binary number to an Integer
 *
 *	@param	_Binary									The bonary number to convert
 *
 *	@return													The Integer
 */
Integer ToInteger(Integer[] _Binary) {
	declare Int = 0;
	foreach (Key => Bit in _Binary) {
		if (Bit != 0) Int += ML::NearestInteger(ML::Pow(2., Key*1.));
	}
	return Int;
}

// ---------------------------------- //
/** Cut a slice of binary number
 *
 *	@param	_Binary										The binary number to cut
 *	@param	_Start										The starting point of the cut
 *	@param	_Count										The number of bits to cut
 *
 *	@return														The slice of binary number
 */
Integer[] Slice(Integer[] _Binary, Integer _Start, Integer _Count) {
	declare SlicedBinary = Integer[];
	declare End = _Start + _Count - 1;
	for (I, _Start, End) {
		if (_Binary.existskey(I)) {
			SlicedBinary.add(_Binary[I]);
		} else {
			SlicedBinary.add(0);
		}
	}
	return SlicedBinary;
}

// ---------------------------------- //
/** Concatenate two binary number
 *
 *	@param	_Binary1									The first binary number
 *	@param	_Binary2									The second binary number
 *
 *	@return														The concatenated binary number
 */
Integer[] Concat(Integer[] _Binary1, Integer[] _Binary2) {
	declare Binary = _Binary1;
	foreach (Bit in _Binary2) {
		Binary.add(Bit);
	}
	return Binary;
}