title: C packing Integer into a buffer RFC 4506
body: <p>I'm trying to implement this <a href="https://www.rfc-editor.org/rfc/rfc4506#section-4.1" rel="nofollow noreferrer">RFC</a>
  4.1.  Integer</p>
  <p>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:</p>
  <pre><code>     int identifier;
  
         (MSB)                   (LSB)
       +-------+-------+-------+-------+
       |byte 0 |byte 1 |byte 2 |byte 3 |                      INTEGER
       +-------+-------+-------+-------+
       &lt;------------32 bits------------&gt;
  </code></pre>
  <p>and here's my code I need to know if there is a better way to do that ?</p>
  <pre><code>void packInteger(char *buf,long int i)
  {
      if(i&gt;=0) {
          *buf++ = i&gt;&gt;24;
          *buf++ = i&gt;&gt;16;
          *buf++ = i&gt;&gt;8;
          *buf++ = i;
      }
      if(i&lt;0) {
          i = i*-1;
          i =  1 + (unsigned int)(0xffffffffu - i);
          buf[0] = (unsigned int)i&gt;&gt;24;
          buf[1] = (unsigned int)i&gt;&gt;16;
          buf[2] = (unsigned int)i&gt;&gt;8;
          buf[3] = (unsigned int)i;
      }   
  }
  long int unpackInteger(char *buf)
  {
      unsigned long int i2 = ((unsigned long int)buf[0]&lt;&lt;24) |
                             ((unsigned long int)buf[1]&lt;&lt;16) |
                             ((unsigned long int)buf[2]&lt;&lt;8)  |
                             buf[3];
      long int i;
      // change unsigned numbers to signed
      if (i2 &lt;= 0x7fffffffu) { i = i2; }
      else { i = -1 - (long int)(0xffffffffu - i2); }
      return i;
  }
  int main(void) 
  {
      char buf[4];
      packInteger(buf,-31);
      printf(&quot;%u %u %u %u\n&quot;,buf[0],buf[1],buf[2],buf[3]);
      long int n = unpackInteger(buf);
      printf(&quot;%ld&quot;,n);
      return 0;
  }
  </code></pre>
  <p>if someone on 64 bit system is it working or noT ?</p>
  <p>version 2</p>
  <pre><code>void packInteger(unsigned char *buf,long int i)
  {
  unsigned long int j = i; // this will convert to 2's complement
  *buf++ = i&gt;&gt;24;
  *buf++ = i&gt;&gt;16;
  *buf++ = i&gt;&gt;8;
  *buf++ = i;
  }
  </code></pre>