Frage

I have created two functions that sum and subtract the numeric values of two chars and return the char of the result in PHP. It's something like this:

function sumchars($c1, $c2) {
    return chr(ord($c1) + ord($c2));
}

function subchars($c1, $c2) {
    return chr(ord($c1) - ord($c2));
}

Well, I also created these two function in Java and they are supposed to work as the PHP ones.

public static String sumchars(char c1, char c2) {
    return (char)((int)c1 + int(c2));
}

public static String subchars(char c1, char c2) {
    return (char)((int)c1 -+ int(c2));
}

It seems like the PHP function chr() knows how to treat results that are outside the ASCII range (greater than 255) and also those that are negative (less than 0). Not the same happens in Java (where instead of a function I just cast the integer result). I know that I could create a simple function for that but I wonder if there's already one. I want these functions to be very fast and I would prefer to use something already implemented rather than a function created by me.

Thanks in advance for your recommendations!

War es hilfreich?

Lösung

Just add 256 to make sure you don't have negative values and then mod that result by 256 to make sure it's not larger than 256. ( alternatively, use if else statements ).

public static String sumchars(char c1, char c2) {
    return (char)((((int)c1 + int(c2)) + 256) % 256);
}

public static String subchars(char c1, char c2) {
    return (char)(((int)c1 - int(c2)) + 256) % 256);
}

Andere Tipps

You can use the Character class:

http://docs.oracle.com/javase/6/docs/api/java/lang/Character.html

Character.isLetter()
Character.isDigit()
Character.isLetterOrDigit()

And then determine what to do base on the returned boolean.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top