Core Java

Convert Short to Byte Array

1. Introduction

Converting a short value to a byte array is a common task when dealing with binary data. In this example, I will demonstrate short byte array conversion in the following ways:

2. Setup

In this step, I will create a maven project with the Junit library.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.zheng.demo</groupId>
	<artifactId>convert_short_to_bytearray</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<release>17</release>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<!-- junit 5 -->
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<version>5.5.2</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

3. Junit Test Class

In this step, I will convert a short value to a byte array with three tests.

TestConvertShortToByteArray.java

package convert_short_to_bytearray;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import org.junit.jupiter.api.Test;

public class TestConvertShortToByteArray {

	short shortValue = 32767;
	byte[] expectedByteArray = { 127, -1 };

	@Test
	public void convertToByteArray_via_ByteBuffer() {
		byte[] byteArray = ByteBuffer.allocate(Short.BYTES).putShort(shortValue).array();

		assertArrayEquals(expectedByteArray, byteArray);
	}

	@Test
	public void convertToByteArray_via_DataOutputStream() throws IOException {
		try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
				DataOutputStream dos = new DataOutputStream(baos)) {
			
			dos.writeShort(shortValue);
			byte[] byteArray = baos.toByteArray();
			
			assertArrayEquals(expectedByteArray, byteArray);
		}
	}

	@Test
	public void convertToByteArray_via_BitShiftOperator() {
		byte[] byteArray = new byte[Short.BYTES];
		byteArray[0] = (byte) (shortValue >> 8);
		byteArray[1] = (byte) shortValue;

		assertArrayEquals(expectedByteArray, byteArray);
	}
}
  • line 18: convertToByteArray_via_ByteBuffer – utilizes the java.nio.ByteBuffer class. See step 3.1 for a detailed explanation.
  • line 25: convertToByteArray_via_DataOutputStream – uses java.io.ByteArrayOutputStream class. See step 3.2 for a detailed explanation.
  • line 37: convertToByteArray_via_BitShiftOperator – uses the signed right shift operator. See step 3.3 for a detailed explanation.

3.1 Short Byte Array Conversion via ByteBuffer

We will convert a short to a byte array with three steps.

  • First, create a ByteBuffer object with the size of Short.BYTES via ByteBuffer.allocate(Short.BYTES)
  • Second, write the given short value via putShort(shortValue).
  • Last, invoke the array method to convert to a byte array.

3.2 Short Byte Array Conversion via ByteArrayOutputStream

Following three steps to convert a short into a byte array.

  • First, create a ByteArrayOutputStream and DataOutputStream objects.
  • Then write the short value via dos.writeShort(shortValue).
  • Finally, convert to a byte array via baos.toByteArray();

3.3 Short Byte Array Conversion via Bit Shift Operator

A short in Java is a 16-bit signed integer and takes 2 bytes in memory. The first byte stores the high-order bits and the second byte stores the lower-order bits. In this step, I will use the “signed right shift operator” ( >>) to create a byte array from a short value.

  • The shortValue >> 8 shifts the bits of shortValue to the right by 8 positions. This operation effectively isolates the most significant byte of the shortValue as the most significant byte (high-order byte) of a short is stored in the element at index 0 of byte[].
  • The least significant byte (low-order byte) is stored in the element at index 1 of byte[]. The (byte) again casts shortValue to a byte, truncating the higher-order bits that do not fit into a byte.

4. Run Test

In this step, I will run the tests and verify the tests are passed.

Figure 1. Unit Tests Result

5. Conclusion

In this example, I demonstrated short byte array conversion in the following ways:

6. Download

This was an example of a maven project which converts a short value into a byte array.

Download
You can download the full source code of this example here: Convert Short to Byte Array

Mary Zheng

Mary graduated from the Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She worked as a lead Software Engineer in the telecommunications sector where she led and worked with others to design, implement, and monitor the software solution.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button