Add read digits util

This commit is contained in:
Anton Tananaev
2026-05-06 21:08:05 -07:00
parent 3d64725acf
commit efd2e18682
3 changed files with 19 additions and 10 deletions

View File

@@ -87,4 +87,13 @@ public final class BufferUtil {
return buf.readCharSequence(length, StandardCharsets.US_ASCII).toString();
}
public static String readDecimalDigits(ByteBuf buf, int byteCount) {
StringBuilder builder = new StringBuilder(byteCount * 2);
for (int i = 0; i < byteCount; i++) {
int b = buf.readUnsignedByte();
builder.append(b / 10).append(b % 10);
}
return builder.toString();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013 - 2018 Anton Tananaev (anton@traccar.org)
* Copyright 2013 - 2026 Anton Tananaev (anton@traccar.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import io.netty.channel.Channel;
import org.traccar.BaseProtocolDecoder;
import org.traccar.session.DeviceSession;
import org.traccar.Protocol;
import org.traccar.helper.BufferUtil;
import org.traccar.helper.DateBuilder;
import org.traccar.model.Position;
@@ -51,16 +52,9 @@ public class M2mProtocolDecoder extends BaseProtocolDecoder {
firstPacket = false;
StringBuilder imei = new StringBuilder();
for (int i = 0; i < 8; i++) {
int b = buf.readByte();
if (i != 0) {
imei.append(b / 10);
}
imei.append(b % 10);
}
String imei = BufferUtil.readDecimalDigits(buf, 8).substring(1);
getDeviceSession(channel, remoteAddress, imei.toString());
getDeviceSession(channel, remoteAddress, imei);
} else {

View File

@@ -38,4 +38,10 @@ public class BufferUtilTest {
assertEquals(3, BufferUtil.indexOf("de", buf, 2, 6));
}
@Test
public void testReadDecimalDigits() {
ByteBuf buf = Unpooled.wrappedBuffer(DataConverter.parseHex("0b1621"));
assertEquals("112233", BufferUtil.readDecimalDigits(buf, 3));
}
}