mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-23 20:44:39 +08:00
Add EndianConverter
algorithm (#5751)
This commit is contained in:
@ -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);
|
||||
}
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user