0
votes

A have a program that written on C++. It receive byte array and convert it to value. I have some experience with C++ but after some days of research I realized that not enough.

quint32 id = getWORD(&rawData[1]);

in my case rawData = {0x03, 0xAD, 0x1D, 0xFA, 0x03, 0x02, 0x00, 0x00, 0x00, 0x3D, 0xB3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6A, 0x00, 0x00}

uint32_t getWORD(const char* buf)
{
    uint32_t val;
    memcpy(&val, buf, sizeof(val));
    return val;
}

If I understand correctly this method just convert this byte to uint32_t type

And then, result is:

QString result = QString("%1").arg((quint32) id, 8, 16, QChar('0')).toUpper()

I have read about arg function here but there are dozens of different constructors with different arguments, and I have never saw something similar in Java or Kotlin, so have no idea how to realize it.

Will appreciate any hint

UPD:

byte[] bytes = {(byte) 0xAD, (byte) 0x1D, (byte) 0xFA, (byte) 0x03};
int result = ByteBuffer.wrap(bytes).getInt(); // = -1390544381

But negative value not looks like correct ID of device

I have already think about String.format but according to documentation of QString:

QString QString::arg(uint a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const

The base argument specifies the base to use when converting the integer a into a string. The base must be between 2 and 36.

If fillChar is '0' (the number 0, ASCII 48), the locale's zero is used. For negative numbers, zero padding might appear before the minus sign.

So I'm not sure that String.format can help in this case

1
@Hulk thanks. I have updated questionIvan Ardelian

1 Answers

0
votes

In java, as all java integer types are signed, when printing int with the default format, it will be interpreted as a negative number. However, the formatting functions for rendering hexadecimal numbers treat it as unsigned.

You have not provided sample input and output, but it seems that an appropriate conversion character of a java format string would be either X or x, depending on whether characters are upper- or lowercase. Leading space is filled with blanks by default:

public static void main(String[] args) {
    byte[][] inputs = { 
            { (byte) 0xAD, (byte) 0x1D, (byte) 0xFA, (byte) 0x03 },
            { (byte) 0x00, (byte) 0x00, (byte) 0xFA, (byte) 0x03 }};

    for (byte[] bytes : inputs) {

        int result = ByteBuffer.wrap(bytes).getInt(); // = -1390544381
        System.out.println("int:    \"" + String.format("%12d", result) + "\"");
        System.out.println("hex 8:  \"" + String.format("%8X", result) + "\"");
        // equivalent, just to demonstrate positional arguments
        System.out.println(String.format("%2$5s:  \"%1$8X\"", result, "hex 8"));
    }
}

Output:

int:    " -1390544381"
hex 8:  "AD1DFA03"
hex 8:  "AD1DFA03"
int:    "       64003"
hex 8:  "    FA03"
hex 8:  "    FA03"