Skip to content

Instantly share code, notes, and snippets.

@ksvbka
Last active August 29, 2015 14:19
Show Gist options
  • Save ksvbka/35ba5977a27c46861f50 to your computer and use it in GitHub Desktop.
Save ksvbka/35ba5977a27c46861f50 to your computer and use it in GitHub Desktop.
My math
/*
Macro to convert the MSB/LSB of a 16-bit value to a 8-bit value
*/
#define GET_16BIT_MSB( x ) ( (uint8_t)( ( ( (uint16_t)(x) ) >> 8 ) & 0xFF ) )
#define GET_16BIT_LSB( x ) ( (uint8_t)( ( (uint16_t)(x) ) & 0xFF ) )
/* macro to write the 16-bit value into an 8-bit buffer */
#define BUF_SET_16BIT( buf, value ) \
do { \
((uint8_t *)(buf))[ 0 ] = GET_16BIT_MSB(value); \
((uint8_t *)(buf))[ 1 ] = GET_16BIT_LSB(value); \
} while ( 0 )
/* macro to read a 16-bit value from an 8-bit buffer */
#define BUF_GET_16BIT( buf ) \
( ( ((uint16_t)( ((uint8_t *)(buf))[ 0 ] ) ) << 8 ) \
| ( ((uint16_t)( ((uint8_t *)(buf))[ 1 ] ) ) & 0xFF ) \
)
/*
Convert an unsigned int to signed int.
*/
int16_t unsignedToSigned(uint16_t val)
{
if(val > 0x8000)
val = -((65535 - val) +1);
return val;
}
/*
Check Prime number
*/
unsigned char isPrimeNumber(int n)
{
if(n < 2) return 0;
int temp = (int)sqrt(n);
for(i = 2; i < temp; i++)
if(n % i == 0) return 0;
return 1;
}
/*
Find Greatest Common Divisor - GCD
*/
int GCD(int a, int b)
{
while(b != 0)
{
int temp = a % b;
a = b; b = temp;
}
return b;
}
unsigned short u16ToLittleEndian( unsigned short u16input )
{/* Use this function to convert a 16-bit number into little endian. */
return( (u16input >> 8) ^ (u16input << 8) );
}// end u16ToLittleEndian()
unsigned long u32ToLittleEndian( unsigned long u32input )
{/* Use this function to convert a 32-bit number into little endian. */
return( (u32input >> 24)
^ ( (u32input >> 8) & 0x000FF00 )
^ ( (u32input << 8) & 0x00FF0000 )
^ ( (u32input << 24) & 0xFF000000 )
);
}// end u32ToLittleEndian()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment