0

I hope someone could help me. I need to write and read bytes in HEX. I get an INTEGER

int key = 99;
byte[] bytekey = new byte[1];
bytekey[0] = (byte) key;

gives me in HEX 63

but in want 99 in HEX

bytekey [0] = (byte)(0x99);

gives me in HEX 99

I try for hours but didn't find a way for something like this.

bytekey [0] = (byte)(0xkey);

Now I created this function as solution:

private static int getBase10(int inputKey) {
    int base = 16;
    String keyString = Integer.toString(inputKey);
    int key = Integer.parseInt(keyString, base);
    return key;
}
evoco
  • 1
  • 1
  • There are multiple issues with your code. It already starts with the fact that you are assigning `int`s to `byte`. Java `byte`s are **signed**. So this will naturally offset your output. Also, it sounds like a XY problem. What do you actually want to achieve here? Converting a hex-string like `"AF03C4"` into the corresponding byte array, assuming that bytes go from `0` to `255` (and not like in Java, from `-128` to `+127`)? – Zabuzard Sep 28 '20 at 15:38
  • What about writing `int key = 0x99`? Otherwise it sounds like your asking, I want to take an integer (doesn't have a base) write it in base 10 then treat that base 10 number as a base 16. – matt Sep 28 '20 at 16:17
  • Thank you for this hint. I need to send a variable in a message with the number 1 to 99 in HEX. I am able to send Integers from 1 to 9, because they are always the same. But with higher numbers the hex representation is different. how do I get the INTEGER variable to work in – evoco Sep 28 '20 at 16:21
  • Thank you. This realy works. int key = 0x99. The only problem is, this key is the variable I receive. So i need to convert the int 99 into int 0x99 (and int 50 into int 0x50 ... and so on) – evoco Sep 28 '20 at 16:33
  • You're missing the point. An integer doesn't have a base. (technically it is twos compliment) So when you write `int key = 0x99;` It creates an int based on that hexadecimal value, in base 10 it is 153. So what your suggesting is that somebody wrote `int key = 99` but they meant `0x99`? What about `int key = 0x9a` you couldn't write `int key = 9a;` because 'a' is not a digit in base 10. – matt Sep 28 '20 at 16:48
  • I wrote you the "zeroX" function that makes the conversion you're asking for. If they re-open this question Ill make it an answer. https://ideone.com/HpZ60E – matt Sep 28 '20 at 16:58
  • Thank you for the hint with the base. I added my solution to my question. This works for me with numbers from 1 to 99 – evoco Sep 29 '20 at 06:52
  • Why reopen? What changed? Could we see a clear input+expected output example, because I do not follow yet. – Zabuzard Sep 29 '20 at 06:56
  • @Zabuzard they've put an answer in their question even that describes what they want. Which is very strange, maybe it is some sort of exercise? – matt Sep 29 '20 at 07:06

0 Answers0