java - 在 Java 中填充字节数组

标签 java bytearray voip rtp

对于我正在处理的项目的一部分,我正在实现一个 RTPpacket,我必须在其中用 RTP header 字段填充字节 header 数组。

  //size of the RTP header:
  static int HEADER_SIZE = 12; // bytes

  //Fields that compose the RTP header
  public int Version; // 2 bits
  public int Padding; // 1 bit
  public int Extension; // 1 bit
  public int CC; // 4 bits
  public int Marker; // 1 bit
  public int PayloadType; // 7 bits
  public int SequenceNumber; // 16 bits
  public int TimeStamp; // 32 bits
  public int Ssrc; // 32 bits

  //Bitstream of the RTP header
  public byte[] header = new byte[ HEADER_SIZE ];

这是我的方法:

/*      
 * bits 0-1: Version
 * bit    2: Padding 
 * bit    3: Extension
 * bits 4-7: CC
 */
header[0] = new Integer( (Version << 6)|(Padding << 5)|(Extension << 6)|CC ).byteValue();

/* 
 * bit    0: Marker
 * bits 1-7: PayloadType
 */
header[1] = new Integer( (Marker << 7)|PayloadType ).byteValue();

/* SequenceNumber takes 2 bytes = 16 bits */
header[2] = new Integer( SequenceNumber >> 8 ).byteValue();
header[3] = new Integer( SequenceNumber ).byteValue();

/* TimeStamp takes 4 bytes = 32 bits */
for ( int i = 0; i < 4; i++ )
    header[7-i] = new Integer( TimeStamp >> (8*i) ).byteValue();

/* Ssrc takes 4 bytes = 32 bits */
for ( int i = 0; i < 4; i++ )
    header[11-i] = new Integer( Ssrc >> (8*i) ).byteValue();

还有其他可能“更好”的方法吗?

最佳答案

我想我会使用 ByteBuffer

ByteBuffer buf = ByteBuffer.wrap(header);
buf.setOrder(ByteOrder.BIG_ENDIAN);
buf.put((byte)((Version << 6)|(Padding << 5)|(Extension << 6)|CC));
buf.put((byte)((Marker << 7)|PayloadType));
buf.put((short)SequenceNumber);
buf.put(TimeStamp);
buf.put(Ssrc);

关于java - 在 Java 中填充字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2614446/

相关文章:

java.lang.ClassCastException : java. util.Arrays$ArrayList 无法在 DAO 中转换为 java.lang.Integer

Python 可写缓冲区/memoryview 到数组/bytearray/ctypes 字符串缓冲区

iOS 10 : How to show incoming VOIP call notification when app is in background?

ios - 如何为 PJSUA 应用程序运行单独创建日志文件?

java - 在JAVA中将短数组转换为字节数组

ios - 使用 VoIP 在 iOS 上节省电池电量

java - 在 Apache Beam 上确认 Google Pub/Sub 消息

java - 如何在 Android Studio 中更改提示文本颜色?

java - 运行index.jsp时无法显示表格

java - 在 Java 中比较 2 个 x509 证书