
///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                               CPU Control                                 //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////
// (c) 2021 Miroslav Nemecek, Panda38@seznam.cz, panda38.sweb.cz
// This source code may be used freely without restrictions for any purpose,
// including commercial.

// create or verify bit tables (returns FALSE on table error)
bool InitBitTab();

// reverse bits
u8 Reverse8(u8 val);
u16 Reverse16(u16 val);
u32 Reverse32(u32 val);
u64 Reverse64(u64 val);

// get numer of bits of value (logarithm, returns position of highest bit + 1: 0..64)
u8 Bits8(u8 val);
u8 Bits16(u16 val);
u8 Bits32(u32 val);
u8 Bits64(u64 val);

// get number of high bits of value (returns top offset of lowest bit + 1: 0..64)
u8 HighBits8(u8 val);
u8 HighBits16(u16 val);
u8 HighBits32(u32 val);
u8 HighBits64(u64 val);

// rotate bits in DWORD right (carry lower bits to higher bits)
INLINE u32 ror(u32 val, u32 num)
{
//	__asm volatile (" ror %0, %0, %1\n" : "+r" (val) : "r" (num));
//	return val;
	return (val >> num) | (val << (32 - num));
}

INLINE u16 ror16(u16 val, int num)
{
	return (u16)((val >> num) | (val << (16 - num)));
}

INLINE u8 ror8(u8 val, int num)
{
	return (u8)((val >> num) | (val << (8 - num)));
}

// rotate bits in DWORD left (carry higher bits to lower bits)
INLINE u32 rol(u32 val, u32 num)
{
//	num = 32 - num;
//	__asm volatile (" ror %0, %0, %1\n" : "+r" (val) : "r" (num));
//	return val;
	return (val << num) | (val >> (32 - num));
}

INLINE u16 rol16(u16 val, int num)
{
	return (u16)((val << num) | (val >> (16 - num)));
}

INLINE u8 rol8(u8 val, int num)
{
	return (u8)((val << num) | (val >> (8 - num)));
}

/*
// asm cortex_7m and higher
#if defined(USE_ASM) && \
	((defined (__ARM_ARCH_7M__) && (__ARM_ARCH_7M__== 1)) || \
	(defined (__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__== 1)) || \
	(defined (__ARM_ARCH_8M_MAIN__) && (__ARM_ARCH_8M_MAIN__== 1)) || \
	(defined (__ARM_ARCH_8M_BASE__) && (__ARM_ARCH_8M_BASE__== 1)))
#define _CORTEX_M7_MORE
#endif

// reverse bits on Cortex7m and higher
INLINE u8 Reverse8(u32 val)
{
	u32 res;
	__asm volatile (" rbit %0, %1\n" : "=r" (res) : "r" (val));
	return (u8)(res >> 24);
}

INLINE u16 Reverse16(u32 val)
{
	u32 res;
	__asm volatile (" rbit %0, %1\n" : "=r" (res) : "r" (val));
	return (u16)(res >> 16);
}

INLINE u32 Reverse(u32 val)
{
	u32 res;
	__asm volatile (" rbit %0, %1\n" : "=r" (res) : "r" (val));
	return res;
}
*/
