/*
 * Helpers.c
 *
 *  Created on: Jan 9, 2015
 *      Author: B52414
 */
#include <stdio.h>
#include <string.h>
#include "PE_Types.h"
#include "PE_Error.h"
#include "Helpers.h"

/**
 * Returns string with binary representation of value.
 *
 * @param result Destination string for storing binary representation of value.
 * @return Returns pointer to destination string.
 */
char* uintToBinary(char result[], uint32_t value, uint8_t valueLength)
{
	uint16_t i;
	char binStr;
	uint32_t start = 1 << (valueLength - 1);

	result[0] = '\0';

	for (i = start; i > 0; i >>= 1) {
		binStr = (value & i) ? '1' : '0';
		strncat(result, &binStr, 1);
		// Append space after 4 bits
		if (i == 0x10000000 || i == 0x1000000 || i == 0x100000 || i == 0x10000 ||
				i == 0x1000 || i == 0x0100 || i == 0x0010) {
			strncat(result, " ", 1);
		}
	}
	return result;
}

char* uint16ToBinary(char result[20], uint16_t value)
{
	return uintToBinary(result, value, 16);
}

char* uint8ToBinary(char result[10], uint16_t value)
{
	return uintToBinary(result, value, 8);
}
