fix bytesToFloat bug

This commit is contained in:
looly
2021-12-12 11:43:56 +08:00
parent a9bd7c3bb4
commit 60901d5815
5 changed files with 193 additions and 57 deletions

View File

@@ -6,6 +6,7 @@ import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.HexUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
@@ -343,4 +344,13 @@ public class ConvertTest {
final BigDecimal bigDecimal = Convert.toBigDecimal(str);
Assert.assertEquals(str, bigDecimal.toPlainString());
}
@Test
public void toFloatTest(){
// https://gitee.com/dromara/hutool/issues/I4M0E4
String hex2 = "CD0CCB43";
final byte[] value = HexUtil.decodeHex(hex2);
final float f = Convert.toFloat(value);
Assert.assertEquals(406.1F, f, 2);
}
}

View File

@@ -10,7 +10,7 @@ public class ByteUtilTest {
@Test
public void intAndBytesLittleEndianTest() {
// 测试 int 转小端序 byte 数组
int int1 = 1417;
int int1 = RandomUtil.randomInt();
byte[] bytesInt = ByteUtil.intToBytes(int1, ByteOrder.LITTLE_ENDIAN);
int int2 = ByteUtil.bytesToInt(bytesInt, ByteOrder.LITTLE_ENDIAN);
@@ -28,7 +28,7 @@ public class ByteUtilTest {
@Test
public void intAndBytesBigEndianTest() {
// 测试 int 转大端序 byte 数组
int int2 = 1417;
int int2 = RandomUtil.randomInt();
byte[] bytesInt = ByteUtil.intToBytes(int2, ByteOrder.BIG_ENDIAN);
// 测试大端序 byte 数组转 int
@@ -65,9 +65,30 @@ public class ByteUtilTest {
Assert.assertEquals(long1, long2);
}
@Test
public void floatAndBytesLittleEndianTest() {
// 测试 long 转 byte 数组
float f1 = (float) RandomUtil.randomDouble();
byte[] bytesLong = ByteUtil.floatToBytes(f1, ByteOrder.LITTLE_ENDIAN);
float f2 = ByteUtil.bytesToFloat(bytesLong, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(f1, f2, 2);
}
@Test
public void floatAndBytesBigEndianTest() {
// 测试大端序 long 转 byte 数组
float f1 = (float) RandomUtil.randomDouble();
byte[] bytesLong = ByteUtil.floatToBytes(f1, ByteOrder.BIG_ENDIAN);
float f2 = ByteUtil.bytesToFloat(bytesLong, ByteOrder.BIG_ENDIAN);
Assert.assertEquals(f1, f2, 2);
}
@Test
public void shortAndBytesLittleEndianTest() {
short short1 = 122;
short short1 = (short) RandomUtil.randomInt();
byte[] bytes = ByteUtil.shortToBytes(short1, ByteOrder.LITTLE_ENDIAN);
short short2 = ByteUtil.bytesToShort(bytes, ByteOrder.LITTLE_ENDIAN);