BinaryReader ReadString specifying length?

后端 未结 2 1358
梦毁少年i
梦毁少年i 2021-01-14 07:17

I\'m working on a parser to receive UDP information, parse it, and store it. To do so I\'m using a BinaryReader since it will mostly be binary information. Some

2条回答
  •  攒了一身酷
    2021-01-14 08:13

    Unless they specifically say 'int' or 'Int32', they just mean an integer as in a whole number.

    By '7 bits at time', they mean that it implements 7-bit length encoding, which seems a bit confusing at first but is actually rather straightforward. Here are some example values and how they are written out using 7-bit length encoding:

    /*
    decimal value   binary value                ->  enc byte 1   enc byte 2   enc byte 3
    85              00000000 00000000 01010101  ->  01010101     n/a          n/a
    1,365           00000000 00000101 01010101  ->  11010101     00001010     n/a
    349,525         00000101 01010101 01010101  ->  11010101     10101010     00010101
    */
    

    The table above uses big endian for no other reason than I simply had to pick one and it's what I'm most familiar with. The way 7-bit length encoding works, it is little endian by it's very nature.

    Note that 85 writes out to 1 byte, 1,365 writes out to 2 bytes, and 349,525 writes out to 3 bytes.

    Here's the same table using letters to show how each value's bits were used in the written output (dashes are zero-value bits, and the 0s and 1s are what's added by the encoding mechanism to indicate if a subsequent byte is to be written/read)...

    /*
    decimal value   binary value                ->  enc byte 1   enc byte 2   enc byte 3
    85              -------- -------- -AAAAAAA  ->  0AAAAAAA     n/a          n/a
    1,365           -------- -----BBB AAAAAAAA  ->  1AAAAAAA     0---BBBA     n/a
    349,525         -----CCC BBBBBBBB AAAAAAAA  ->  1AAAAAAA     1BBBBBBA     0--CCCBB
    */
    

    So values in the range of 0 to 2^7-1 (127) will write out as 1 byte, values of 2^7 (128) to 2^14-1 (16,383) will use 2 bytes, 2^14 (16,384) to 2^21-1 (2,097,151) will take 3 bytes, and so on and so forth.

提交回复
热议问题