C打包整数到缓冲区RFC 4506

时间:2011-09-25 08:01:12

标签: c binary

我正在尝试实施此RFC 4.1。整数

XDR带符号整数是一个32位数据,用于对整数进行编码    范围[-2147483648,2147483647]。整数表示为    两个补码表示法。最重要和最不重要的字节是    分别为0和3。整数声明如下:

     int identifier;

       (MSB)                   (LSB)
     +-------+-------+-------+-------+
     |byte 0 |byte 1 |byte 2 |byte 3 |                      INTEGER
     +-------+-------+-------+-------+
     <------------32 bits------------>

这是我的代码我需要知道是否有更好的方法来做到这一点?

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;
}

如果64位系统上有人正在运行或没有?

第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;
}

1 个答案:

答案 0 :(得分:2)

您应该使用unsigned char作为缓冲区。

在C中转换为unsigned执行数学等价的转换为2s补码,因此您的包函数可以简化:

void packInteger(unsigned char *buf, long int i)
{
    unsigned long u = i;

    buf[0] = (u >> 24) & 0xffUL;
    buf[1] = (u >> 16) & 0xffUL;
    buf[2] = (u >> 8) & 0xffUL;
    buf[3] = u & 0xffUL;
}

你的解包功能似乎很好(改为unsigned char)。