Search code examples
javacharbit-manipulationshort

changing a Char to the short with the same bit structure. (2's complement issue)


I want to Change a Char to the short with the same bit structure. Both are 16 bits

I understand that short are 2s complement if they were 1s complement I could use

if a < 0 {return (short) math.abs a + 2 ^ 15;} else {return (short) a;} //right?

How do I do this to 2s complement negative?

I simply want to be able to manipulate the innards of a Char in the same way as I can a Integer.

If the answer is just add one I am going to become emotional :)


Solution

  • The simple solution is to do

    char ch = ...
    short s = (short) ch;
    char ch2 = (char) s;
    // ch == ch2
    

    Perhaps you imagine it has to be more complicated than it is ;)

    I simply want to be able to manipulate the innards of a Char in the same way as I can a Integer.

    In that case you don't even want a short, you want an int which is even simpler.

    e.g.

    // sum all the chars of a string
    String s = "Hello World";
    int sum = 0;
    for(char ch: s.toCharArray())
        sum += ch;
    

    If the answer is just add one I am going to become emotional

    No, even less than that. :j

    BTW you can do

    char ch = 'A';
    int i = ch + 0;
    int j = ch;