Skip to content

@Bytes

@Bytes is an annotation that converts String or number instances into byte[] instances.

With Strings

When converting strings, the input instance is encoded into a sequence of bytes:

import io.github.scordio.junit.converters.Bytes;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

@ParameterizedTest
@ValueSource(strings = "value")
void test(@Bytes byte[] bytes) {
    assertArrayEquals(new byte[] { 118, 97, 108, 117, 101 }, bytes);
}

The annotation's optional charset attribute configures the charset to use for conversion. If not specified, the JVM default charset is used.

The following source types and target declarations are supported.

Source Type Target Declaration Example
String @Bytes byte[] "a"new byte[] { 97 }
String @Bytes(charset = "UTF-8") byte[] "ä"new byte[] { -61, -92 }

With Numbers

When converting numbers, the input instance is converted into a sequence of bytes using its binary representation:

import io.github.scordio.junit.converters.Bytes;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

@ParameterizedTest
@ValueSource(ints = 0x12345678)
void test(@Bytes byte[] bytes) {
    assertArrayEquals(new byte[] { 0x12, 0x34, 0x56, 0x78 }, bytes);
}

The annotation's optional order attribute configures the byte order to use when converting multibyte values:

  • BIG_ENDIAN (default): the bytes are ordered from most significant to least significant
  • LITTLE_ENDIAN: the bytes are ordered from least significant to most significant

The following source types and target declarations are supported.

Source Type Target Declaration Example
byte/Byte @Bytes byte[] 0x12new byte[] { 0x12 }
short/Short @Bytes byte[] 0x1234new byte[] { 0x12, 0x34 }
short/Short @Bytes(order = LITTLE_ENDIAN) byte[] 0x1234new byte[] { 0x34, 0x12 }
int/Integer @Bytes byte[] 0x12345678new byte[] { 0x12, 0x34, 0x56, 0x78 }
int/Integer @Bytes(order = LITTLE_ENDIAN) byte[] 0x12345678new byte[] { 0x78, 0x56, 0x34, 0x12 }
long/Long @Bytes byte[] 0x123456780A1B2C3DLnew byte[] { 0x12, 0x34, 0x56, 0x78, 0x0A, 0x1B, 0x2C, 0x3D }
long/Long @Bytes(order = LITTLE_ENDIAN) byte[] 0x123456780A1B2C3DLnew byte[] { 0x3D, 0x2C, 0x1B, 0x0A, 0x78, 0x56, 0x34, 0x12 }
float/Float @Bytes byte[] (float) 0x12345678new byte[] { 0x4D, -0x6F, -0x5E, -0x4C }
float/Float @Bytes(order = LITTLE_ENDIAN) byte[] (float) 0x12345678new byte[] { -0x4C, -0x5E, -0x6F, 0x4D }
double/Double @Bytes byte[] (double) 0x123456780A1B2C3DLnew byte[] { 0x43, -0x4E, 0x34, 0x56, 0x78, 0x0A, 0x1B, 0x2C }
double/Double @Bytes(order = LITTLE_ENDIAN) byte[] (double) 0x123456780A1B2C3DLnew byte[] { 0x2C, 0x1B, 0x0A, 0x78, 0x56, 0x34, -0x4E, 0x43 }