1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include <stdio.h>
#include <limits.h>
#if ( CHAR_BIT != 8 || ULONG_MAX != 0xFFFFFFFFul )
#error "Faut CHAR_BIT sur 8 bits et des long sur 32 bits pour que ça marche"
#endif
int putUlongInMsg(unsigned char * msg, size_t pos, size_t size, unsigned long var)
{
int rc = 0;
if (!msg) { rc = -1; }
if (pos > size || (size - pos) < sizeof(unsigned long) ) { rc = -2; }
if (rc >= 0)
{
msg[pos] = (var >> (8 * 3)) & 0xFF; /* MSB ici */
msg[pos+1] = (var >> (8 * 2)) & 0xFF;
msg[pos+2] = (var >> (8 * 1)) & 0xFF;
msg[pos+3] = (var >> (8 * 0)) & 0xFF; /* LSB ici */
}
return rc;
}
int getUlongFromMsg(unsigned char const * msg, size_t pos, size_t size, unsigned long * var)
{
int rc = 0;
if (!msg) { rc = -1; }
if (pos > size || (size - pos) < sizeof(unsigned long) ) { rc = -2; }
if (!var ) { rc = -3; }
if (rc >= 0)
{
*var = 0u;
*var |= ( msg[pos] & 0xFFul ) << (8 * 3);
*var |= ( msg[pos+1] & 0xFFul ) << (8 * 2);
*var |= ( msg[pos+2] & 0xFFul ) << (8 * 1);
*var |= ( msg[pos+3] & 0xFFul ) << (8 * 0);
}
return rc;
}
int main(void)
{
unsigned char msg[60];
unsigned long monLong = 0xDEADBEEF;
unsigned long monLong2;
putUlongInMsg(msg, 0, sizeof(msg)/sizeof(*msg), monLong);
printf("%#lX\n", monLong);
getUlongFromMsg(msg, 0, sizeof(msg)/sizeof(*msg), &monLong2);
printf("%#lX\n", monLong2);
return 0;
} |
Partager