#include "common/binary_utils.hpp"

static bool is_little_endian(){
	unsigned x=0x76543210;
	char* c=(char*)&x;
	return *c==0x10;
}

uint16_t polygun::utils::bytes_to_uint16(const char* data){
	uint16_t output;
	if(is_little_endian()){
		((char*)&output)[0]=data[0];
		((char*)&output)[1]=data[1];
	}
	else{
		((char*)&output)[1]=data[0];
		((char*)&output)[0]=data[1];
	}
	return output;
}

void polygun::utils::uint16_to_bytes(uint16_t data,char* output){
	if(is_little_endian()){
		output[0]=((char*)&data)[0];
		output[1]=((char*)&data)[1];
	}
	else{
		output[1]=((char*)&data)[0];
		output[0]=((char*)&data)[1];
	}
}

uint32_t polygun::utils::bytes_to_uint32(const char* data){
	uint32_t output;
	if(is_little_endian()){
		((char*)&output)[0]=data[0];
		((char*)&output)[1]=data[1];
		((char*)&output)[2]=data[2];
		((char*)&output)[3]=data[3];
	}
	else{
		((char*)&output)[3]=data[0];
		((char*)&output)[2]=data[1];
		((char*)&output)[1]=data[2];
		((char*)&output)[0]=data[3];
	}
	return output;
}

void polygun::utils::uint32_to_bytes(uint32_t data,char* output){
	if(is_little_endian()){
		output[0]=((char*)&data)[0];
		output[1]=((char*)&data)[1];
		output[2]=((char*)&data)[2];
		output[3]=((char*)&data)[3];
	}
	else{
		output[3]=((char*)&data)[0];
		output[2]=((char*)&data)[1];
		output[1]=((char*)&data)[2];
		output[0]=((char*)&data)[3];
	}
}

float polygun::utils::bytes_to_float(const char* data) {
	float output;
	if(is_little_endian()){
		((char*)&output)[0]=data[0];
		((char*)&output)[1]=data[1];
		((char*)&output)[2]=data[2];
		((char*)&output)[3]=data[3];
	}
	else{
		((char*)&output)[3]=data[0];
		((char*)&output)[2]=data[1];
		((char*)&output)[1]=data[2];
		((char*)&output)[0]=data[3];
	}
	return output;
}

void polygun::utils::float_to_bytes(float data, char* output) {
	if(is_little_endian()){
		output[0]=((char*)&data)[0];
		output[1]=((char*)&data)[1];
		output[2]=((char*)&data)[2];
		output[3]=((char*)&data)[3];
	}
	else{
		output[3]=((char*)&data)[0];
		output[2]=((char*)&data)[1];
		output[1]=((char*)&data)[2];
		output[0]=((char*)&data)[3];
	}
}
