Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a byte array in Java

For part of a project I'm working on I am implementing a RTPpacket where I have to fill the header array of byte with RTP header fields.

  //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 ];

This was my approach:

/*      
 * 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();

Any other, maybe 'better' ways to do this?

like image 701
Corleone Avatar asked Apr 10 '10 18:04

Corleone


People also ask

How do you fill an entire array in Java?

Solution. This example fill (initialize all the elements of the array in one short) an array by using Array. fill(arrayname,value) method and Array. fill(arrayname, starting index, ending index, value) method of Java Util class.

How do you assign a byte array in Java?

If you're trying to assign hard-coded values, you can use: byte[] bytes = { (byte) 204, 29, (byte) 207, (byte) 217 }; Note the cast because Java bytes are signed - the cast here will basically force the overflow to a negative value, which is probably what you want.

What is fill () in Java?

fill() method is in java. util. Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array.

What is byte array Java?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..


1 Answers

I think I would use a 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);
like image 106
Maurice Perry Avatar answered Oct 06 '22 01:10

Maurice Perry