Search code examples
javabinarybytebitshort

Replace multiple bits in a short


How can I replace multiple bits in a short in Java?

I'm working on a encryption algorithm where I need to do the following: I got a short and need to apply a series of replacements of 4 bits. Example: if the first 4 bits are 0010, replace them with 0110, if its 1111, replace them with 1100 and so on, the same for the second 4 bits.

What is the best/fastest way to do this? At the moment I convert the short to a String and do it with String replacement but its obviously extremely slow and in my opinion the absolute wrong way.


Solution

  • Bit arithmetic, something like this:

    short s = 191;
    short first = (short) (s & 0x000F);
    short second = (short) ((s >> 4) & 0x000F);
    short third = (short) ((s >> 8) & 0x000F);
    short fourth = (short) ((s >> 12) & 0x000F);
    
    call_the_method_to_convert_each();
    
    s = fourth;
    s = ((short) ((s << 4) | third));
    s = ((short) ((s << 4) | second));
    s = ((short) ((s << 4) | first));