0

I need to extract some information from a Transport Stream like PID, PAT, PMT, etc.

I found an example code to get the PID:

pid = ((buf[1] << 8) | (buf[2] & 0xff)) & 0x1fff;

But I could not understand the reason to get the buf[1] and shift 8 to the left side because to get the PID information I need get the 5 last bits from the buf[1] and all 8 from the buf[2]. I tested the code and the result was good. I just want to understand the mean of this first part: buf[1] << 8 in the equation. Could someone help me?

4

2 回答 2

0

假设您的 PID 是 4660 或 0x1234。所以buf[1] = 0x12buf[2] = 0x34

以免做数学int a = 0x12 | 0x32设置是什么?a = 0x36.

0x36 != 0x1234. 我们需要的是int a = 0x1200 | 0x34得到0x1234

我们如何0x12变成0x1200? 我们将其左移 8 位。(buf[1] << 8)

于 2015-09-19T23:21:40.430 回答
0

PID 为 13 位长。

缓冲区buf是一个byte数组。每个元素为 8 位。

保存 PID 的最小 Java 整数类型是short(16 位有符号整数)。buf[1] << 8在移动时将提升byteint(4 个字节),因此您现在有足够的空间来保存结果。

  buf[1] = XXXXXXXX
  buf[2] = YYYYYYYY

  buf[1] << 8 
  shifted 8 positions to the left in a 32-bit int

  0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X X X X X X X X 0 0 0 0 0 0 0 0| 
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


  (buf[1] << 8) | buf[2]

  0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X X X X X X X X Y Y Y Y Y Y Y Y| 
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


  ((buf[1] << 8) | buf[2]) & 0x1fff

  0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X X X X X Y Y Y Y Y Y Y Y| 
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

buf[2] & 0xff是必需的,因为在 Java 中所有字节都是有符号的,而您需要字节的无符号int值。最后,整个事情都被掩盖0x1fff以保留相关的 13 位。如果你想要一个short,你必须转换结果int

于 2015-09-19T23:28:15.587 回答