Bitwise negation gives unexpected result

后端 未结 5 1221
情歌与酒
情歌与酒 2021-01-05 07:40

I am trying to write a bitwise calculator in java, something that you could input an expression such as ~101 and it would give back 10 however when i run this code



        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 08:29

    Just to elaborate on Edwin's answer a bit - if you're looking to create a variable length mask to develop the bits of interest, you might want some helper functions:

    /**
     * Negate a number, specifying the bits of interest.
     * 
     * Negating 52 with an interest of 6 would result in 11 (from 110100 to 001011).
     * Negating 0 with an interest of 32 would result in -1 (equivalent to ~0).
     * 
     * @param number the number to negate.
     * @param bitsOfInterest the bits we're interested in limiting ourself to (32 maximum).
     * @return the negated number.
     */
    public int negate(int number, int bitsOfInterest) {
        int negated = ~number;
        int mask = ~0 >>> (32 - bitsOfInterest);
        logger.info("Mask for negation is [" + Integer.toBinaryString(mask) + "]");
        return negated & mask;
    }
    
    /**
     * Negate a number, assuming we're interesting in negation of all 31 bits (exluding the sign).
     * 
     * Negating 32 in this case would result in ({@link Integer#MAX_VALUE} - 32).
     * 
     * @param number the number to negate.
     * @return the negated number.
     */
    public int negate(int number) {
        return negate(number, 31);
    }
    

提交回复
热议问题