Created
October 17, 2012 06:50
-
-
Save CodeShane/3904083 to your computer and use it in GitHub Desktop.
Examples of merging bit-masks with bitwise-or
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.codeshane.examples.java; | |
/* Examples of merging bit-masks with bitwise-or. | |
* Also available via http://snipt.org/vgxg5 | |
* | |
* @author codeshane.com | |
* @version 1 | |
* | |
*/ | |
public class BitwiseOr { | |
public static void main(String[] args) { | |
int bit_0=0x1; | |
int bit_1=0x2; | |
int binary_3=0x3; | |
System.out.println("Provided codeshane.com; CC-0 licensed.)"); | |
System.out.println("== Examples: Using BITWISE-OR '|' to combine bit-masks. =="); | |
System.out.println(); | |
System.out.println(" hex binary Bit-mask"); | |
System.out.println("_base-16_ _base-2_ _result_"); | |
System.out.println(); | |
int bitwise_or = bit_0 | bit_1; | |
System.out.println("0x1 ".concat(Integer.toBinaryString(bit_0))); | |
System.out.println("0x2 ".concat(Integer.toBinaryString(bit_1))); | |
System.out.println("0x1 | 0x2 = ".concat(Integer.toBinaryString(bitwise_or)).concat(" -> Correct (bitwise-or)")); | |
System.out.println(); | |
int bitwise_or_too = bit_1 | binary_3; | |
System.out.println("0x2 ".concat(Integer.toBinaryString(bit_1))); | |
System.out.println("0x3 ".concat(Integer.toBinaryString(binary_3))); | |
System.out.println("0x2 | 0x3 = ".concat(Integer.toBinaryString(bitwise_or_too)).concat(" -> Correct (bitwise-or)")); | |
System.out.println(); | |
System.out.println("== Examples: Breaking bit-masks the easy way, using addition '+' =="); | |
System.out.println(); | |
int add_lucky = bit_0 + bit_1; | |
System.out.println("0x1 ".concat(Integer.toBinaryString(bit_0))); | |
System.out.println("0x2 ".concat(Integer.toBinaryString(bit_1))); | |
System.out.println("0x1 + 0x2 = ".concat(Integer.toBinaryString(add_lucky)).concat(" -> Accidentally correct (add)")); | |
System.out.println(); | |
int add_fail = bit_1 + binary_3; | |
System.out.println("0x2 ".concat(Integer.toBinaryString(bit_1))); | |
System.out.println("0x3 ".concat(Integer.toBinaryString(binary_3))); | |
System.out.println("0x2 + 0x3 = ".concat(Integer.toBinaryString(add_fail)).concat(" -> Incorrect (add)")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment