0

Given an input stream of bytes in the following format, is there a better way of extracting integer values?

The low order 7 bits of a byte to represent the value or part of the value
The high order bit is an "escape" or "continuation" bit

so:

0x7F           0111_1111                      127 (0x7F = 0111_1111)
0x81 0x7F      1000_0001  0111_1111           255 (0xFF = 1111_1111)
0x82 0x80 0x00 1000_0010  1000_0000 0000_0000 32768 (0x8000 = 1000_0000_0000_0000)

Currently I am using:

do {
  in.read(b, 0, 1); // read next byte
  intval = (intval * 0x80) + (b[0] & 0x7F);
} while ((b[0] & 0x80) == 0x80);
EAKAE
  • 153
  • 1
  • 11
  • 3
    This is how I'd do it. I might say `intval << 7` instead of `intval * 0x80`, which I think makes things a bit clearer, and perhaps I'd use `0b` binary literals instead of `0x`. But offhand I think your approach is as good as you can do, unless there are integers in the stream larger than 64 bits. – ajb Nov 26 '13 at 18:03
  • 2
    Note that this is approximately the algorithm used to convert UTF8 into UTF16 and UTF32. If that's what you're trying to do it's probably better to use a standard library routine. – Hot Licks Nov 26 '13 at 18:28
  • 1
    I would use `int b = in.read();` instead of an array or read multiple bytes at once. – Peter Lawrey Nov 26 '13 at 18:44
  • 1
    You can replace `while ((b[0] & 0x80) == 0x80)` with `while(b[0]<0)`; for bytes, the topmost bit is the sign bit. – Holger Nov 26 '13 at 18:46
  • I was actually trying to parse a midi file. I decided to not use any library for practice. @PeterLawrey I declared b as a byte array previously and just redeclared it for this portion. Thanks – EAKAE Nov 26 '13 at 22:05

0 Answers0