56

I am stumped on this and I need some fresh eyes, I'm not sure why this code is doing this.

String string = new String(new char[] {(char) 0x01, (char) 0x02, ... ,(char) 0xFC});

The output is everything it should be up until the last number (the 0xFC) it returns a -4, I know its a hex value, but if I do the same with 252 the decimal value, it gives me a negative as well. I hope this is just a simple solution, and I just can't see it.

Thanks ahead of time.

4
  • 1
    what are you trying to return? Commented Apr 6, 2012 at 20:32
  • So you are trying to creating a String from a character array? Commented Apr 6, 2012 at 20:32
  • 0xFC is a positive integer; the char type is not signed. The resultant codepoint is U+00FC - Latin Small Letter U With Diaeresis. How are you outputting the String? Commented Apr 6, 2012 at 20:42
  • 0xFC results in 252, not -4 here ideone.com/cIi9J Commented Apr 6, 2012 at 20:50

1 Answer 1

159

A string to char array is as simple as

String str = "someString"; 
char[] charArray = str.toCharArray();

Can you explain a little more on what you are trying to do?

* Update *

if I am understanding your new comment, you can use a byte array and example is provided.

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

With the following output

0x65 0x10 0xf3 0x29

Sign up to request clarification or add additional context in comments.

2 Comments

I am trying to send a packet with a byte array or char array to get specific values to the device I have on my closed network. I am making an app remote. just need that array in 9 bytes, to give the specific hex or decimal values.
A nice shortcut of the above is "string".toCharArray(). It can save you a line of code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.