0

If this is a duplicate, first of all, I'm sorry I've been looking all around and I haven't found how to solve my problem (or my head is too messed up).

I think that is better if I throw my problem rather than explain it.

I have an integer value wich is int234. I convert this value to its hex string representation EA. Note that this is "EA", it is a string.

Then I use Integer.parseInt to convert it to 0xEA (which is an hex value, not hex string) and finally I need the ASCII (or character) representation of this value.

The problem is that when I decode it using Integer.toHexString I get C3AA instead of EA

This is the best explanation I've found. But still I don't know how to solve it..

I hope you can help me out! Thanks in advance!

EDIT

I'd like to transmit the int 234 in a UDP datagram that's why I use the conversions. (This UDP channel mainly sends ASCII ("234") but I want an exception to that and once in a while transmit it in ony 1byte) That's why I do all this conversions (maybe it is easier than this, but I think I'm too close the problem that I can't see it with clarity)

I can confortly do it in C but I need to do it in Java. And my head is going crazy.

So 234 toHexString becomes `hex="EA";

// HEX -> ASCII code
    for(int i=0; i<hex.length()-1; i+=2 ){
        String output = hex.substring(i, (i + 2));
        int decimal = Integer.parseInt(output, 16);
        result.append((char)decimal);   
    }
    return result.toString();

As result I get a strange character (the one that @fadden said). Now a question: this value is 2bytes long?

I transmit this odd character and when I use str = Integer.toHexString(prevResult); I get C3AA.

Maybe I'm messing thing up, but what I want is just to transmit 0xEA(byte) and get the int 234 in the other side.

For Example, Let's say I'd like to transmit the word "COMMAND" and append the value 234. Normally I would send "COMMAND234" but now I need the command value to be only one byte long. So the hex representation of what I'd be transmitting would be:

0x67 0x79 0x77 0x77 0x65 0x78 0x68 0xEA C O M M A N D 234

sebasira
  • 1,739
  • 1
  • 22
  • 41
  • Why not leave hex like string and use this code? https://stackoverflow.com/questions/4785654/convert-a-string-of-hex-into-ascii-in-java – Santiago Aug 13 '15 at 02:24
  • I think your linked answer has it exactly: "The ê character is EA, in UTF-8, that would be C3 AA." There is no ASCII encoding for ê. You're getting the UTF-8 encoding. Are you attempting to create a CP-1252 character (https://en.wikipedia.org/wiki/Windows-1252)? – fadden Aug 13 '15 at 04:58
  • Thank you both for your replies. @Santiago I'm using that code, see my edited question. fadden: I don't really undestand what you said, please also look my edited question – sebasira Aug 13 '15 at 11:51

0 Answers0