Add EndianConverter algorithm (#5751)

This commit is contained in:
Hardik Pawar
2024-10-14 13:09:58 +05:30
committed by GitHub
parent 40f2d0cf8e
commit 5a710ea61f
3 changed files with 47 additions and 0 deletions

View File

@ -0,0 +1,23 @@
package com.thealgorithms.conversions;
/**
* Converts between big-endian and little-endian formats.
* Big-endian is the most significant byte first, while little-endian is the least significant byte first.
* Big-endian to little-endian: 0x12345678 -> 0x78563412
*
* Little-endian to big-endian: 0x12345678 -> 0x78563412
*
* @author Hardvan
*/
public final class EndianConverter {
private EndianConverter() {
}
public static int bigToLittleEndian(int value) {
return Integer.reverseBytes(value);
}
public static int littleToBigEndian(int value) {
return Integer.reverseBytes(value);
}
}

View File

@ -0,0 +1,22 @@
package com.thealgorithms.conversions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class EndianConverterTest {
@Test
public void testBigToLittleEndian() {
assertEquals(0x78563412, EndianConverter.bigToLittleEndian(0x12345678));
assertEquals(0x00000000, EndianConverter.bigToLittleEndian(0x00000000));
assertEquals(0x00000001, EndianConverter.bigToLittleEndian(0x01000000));
}
@Test
public void testLittleToBigEndian() {
assertEquals(0x12345678, EndianConverter.littleToBigEndian(0x78563412));
assertEquals(0x00000000, EndianConverter.littleToBigEndian(0x00000000));
assertEquals(0x01000000, EndianConverter.littleToBigEndian(0x00000001));
}
}