开发者

Variable Length Quantity C to Objective-C

How can I convert an int to an VLQ in Objective-C, basically so I can get the Variant like in http://code.google.com/apis/protocolbuffers/docs/encoding.html

I found this (from http://rosettacode.org/wiki/Variable-length_quantity) and would like to know how to convert it to Objective-C?

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#开发者_开发百科define BUFLEN 8

#define MAX_UINT32_AS_VLQ 8
size_t uint32_to_vlq(uint32_t number, uint8_t *buf, size_t buflen)
{
  uint8_t ibuf[MAX_UINT32_AS_VLQ];
  size_t written = 0, i;

  if (buflen == 0) return 0;

  if ( number < 128 )
  {
    *buf = number;
    return 1;
  }

  ibuf[0] = number & 0x7f; 
  written++;
  number >>= 7;
  while(number > 0)
  {
    ibuf[written] = (number & 0x7f) | 0x80;
    number >>= 7;
    written++;
  }

  if (written > buflen) return 0;

  for(i = 0; i < written; i++) buf[i] = ibuf[written-i-1];

  return written;
  }

Thanks in advance


Since Objective-C is a super set of C, you can directly use this C code in your Objective-C code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜