1
\$\begingroup\$

I tried this so far:

public String readchar (Reader input) throws java.io.IOException
{
  int i16 = input.read(); // UTF-16 as int
  if (i16 == -1) return null;
  char c16 = (char)i16; // UTF-16
  if (Character.isHighSurrogate(c16)) {
    int low_i16 = input.read(); // low surrogate UTF-16 as int
    if (low_i16 == -1)
      throw new java.io.IOException ("Can not read low surrogate");
    char low_c16 = (char)low_i16;
    int codepoint = Character.toCodePoint(c16, low_c16);
    return new String (Character.toChars(codepoint));
  }
  else 
    return Character.toString(c16);
}

But it contains unsafe casts. I have no idea how to avoid them. Is it possible?

\$\endgroup\$
2
  • \$\begingroup\$ What do you mean by unsafe casts? Casting from int to char will never crash, and because of your ints coming from input.read(); you won't lose any information by the cast. \$\endgroup\$
    – jlordo
    Commented Jun 28, 2013 at 13:10
  • \$\begingroup\$ @jlordo I mean with unsafe a loose of data, because int does not fit into char. \$\endgroup\$
    – ceving
    Commented Jul 2, 2013 at 10:09

1 Answer 1

1
\$\begingroup\$

The javadoc of the read method states:

Returns: The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached

The char primative is "a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive)."

(emphasis mine)

It would appear that your two C-style casts are safe.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.