#include  "includes.h"

// 颠倒字节顺序
uint16_t ntohs(uint16_t n)
{
	uint8_t b1 = n >> 8;
	uint8_t b0 = n & 0xFF;
	
	return (b0 << 8) | b1;
}

uint32_t ntohl(uint32_t n)
{
	uint8_t b3 = n >> 24;
	uint8_t b2 = (n >> 16) & 0xFF;
	uint8_t b1 = (n >> 8) & 0xFF;
	uint8_t b0 = n & 0xFF;
	
	return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
}

float ntohf(float f)
{
	uint32_t n;
	float v;
	
	memmove(&n, &f, 4);
	n = ntohl(n);
	memmove(&v, &n, 4);
	
	return v;
}

uint16_t Byte2IntS(uint8_t *buf, int pos)
{
	return (uint16_t)(buf[pos] | (buf[pos + 1] << 8));
}

void Int2ByteS(uint8_t *buf, int pos, uint16_t val)
{
	buf[pos] = (uint8_t) (val & 0xFF);
	buf[pos + 1] = (uint8_t)((val >> 8) & 0xFF);
}

uint32_t Byte2IntL(uint8_t *buf, int pos)
{
	return (uint32_t)(buf[pos] | (buf[pos + 1] << 8) | (buf[pos + 2] << 16) | (buf[pos + 3] << 24));
}

void Int2ByteL(uint8_t *buf, int pos, uint32_t val)
{
	buf[pos] = (uint8_t)(val & 0xFF);
	buf[pos + 1] = (uint8_t)((val >> 8) & 0xFF);
	buf[pos + 2] = (uint8_t)((val >> 16) & 0xFF);
	buf[pos + 3] = (uint8_t)((val >> 24) & 0xFF);
}

// MODBUS的CRC算法
u16 MODBUS_RTU_CRC16(u8 *puchMsg, u16 usDataLen)
{
    u16 crc = 0xFFFF;
    u8 i;
    
	while (usDataLen--)   // 传输消息缓冲区
    {
        crc ^= *puchMsg++;
        for(i = 0; i < 8; i++)
        {
            if(crc & 0x0001)
            {
                crc >>= 1;
                crc ^= 0xA001;
            }
            else
            {
                crc >>= 1;
            }
        }
    }

    // 交换高低字节顺序
    return ((crc & 0xFF) << 8) | ((crc >> 8) & 0xFF);
}
