1

I want to read block wise data of NFC tag. For which the command is a byte array and it needs block number.

public static byte[] readSingleBlockCmd(int blockNo) {
        byte[] cmd = new byte[3];
        cmd[0] = (byte) 0x02;//flag
        cmd[1] = (byte) 0x23;//cmd
        cmd[2]= (byte)blockNo;

        return cmd;

    }
  • How can I change the int blockNo to its hexadecimal value , which can be cast to byte .I want the byte value and not an byte []

I have gone through the following links

Convert integer into byte array (Java)

How to autoconvert hexcode to use it as byte[] in Java?

Java integer to byte array

Thanks!

Community
  • 1
  • 1
Rachita Nanda
  • 4,509
  • 9
  • 42
  • 66
  • Isn't your question answered by those links? If not, update your question to explain why and what you are having trouble with specifically. – Radiodef May 26 '15 at 17:20
  • Let's clear some things up: "Hexadecimal" is an encoding, specifically for how to write the number out as a String. 0x25 is hexadecimal encoded. But the number itself is still 37 (in base 10), and it is an int or a byte or whatever. You're not using any Strings here, so please forget about the "hexadecimal" part of your question and please ask again, because I don't know what you have in mind. – dcsohl May 26 '15 at 17:28

1 Answers1

3

Converting an integer (in decimal) to hex can be done with the following line:

String hex = Integer.toHexString(blockNo);

Then to convert it to byte, you can use

Byte.parseByte(hex,16);

But if all you wanted to do is convert the parameter to bytes:

Byte.parseByte(blockNo);

would work too I guess. Correct me if I'm wrong.

Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33
  • Exactly, it's supposed to do nothing. it is the same as the last line that I mentioned. But since he wants a hexadecimal, I suggested that he could do it with the inbuilt function to convert to into a string. – Anindya Dutta May 26 '15 at 17:36