I'm trying to implement this RFC 4.1. Integer
An XDR signed integer is a 32-bit datum that encodes an integer in the range [-2147483648,2147483647]. The integer is represented in two's complement notation. The most and least significant bytes are 0 and 3, respectively. Integers are declared as follows:
int identifier;
(MSB) (LSB)
+-------+-------+-------+-------+
|byte 0 |byte 1 |byte 2 |byte 3 | INTEGER
+-------+-------+-------+-------+
<------------32 bits------------>
and here's my code I need to know if there is a better way to do that ?
void packInteger(char *buf,long int i)
{
if(i>=0) {
*buf++ = i>>24;
*buf++ = i>>16;
*buf++ = i>>8;
*buf++ = i;
}
if(i<0) {
i = i*-1;
i = 1 + (unsigned int)(0xffffffffu - i);
buf[0] = (unsigned int)i>>24;
buf[1] = (unsigned int)i>>16;
buf[2] = (unsigned int)i>>8;
buf[3] = (unsigned int)i;
}
}
long int unpackInteger(char *buf)
{
unsigned long int i2 = ((unsigned long int)buf[0]<<24) |
((unsigned long int)buf[1]<<16) |
((unsigned long int)buf[2]<<8) |
buf[3];
long int i;
// change unsigned numbers to signed
if (i2 <= 0x7fffffffu) { i = i2; }
else { i = -1 - (long int)(0xffffffffu - i2); }
return i;
}
int main(void)
{
char buf[4];
packInteger(buf,-31);
printf("%u %u %u %u\n",buf[0],buf[1],buf[2],buf[3]);
long int n = unpackInteger(buf);
printf("%ld",n);
return 0;
}
if someone on 64 bit system is it working or noT ?
version 2
void packInteger(unsigned char *buf,long int i)
{
unsigned long int j = i; // this will convert to 2's complement
*buf++ = i>>24;
*buf++ = i>>16;
*buf++ = i>>8;
*buf++ = i;
}