Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Core Java Code Examples

Byte to Binary Conversion

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
Byte to Binary Conversion import java.io.*; /** * BinCat is a simple class for reading bytes and * writting them back out in binary representation. */ public class BinCat { BufferedInputStream brIn; PrintStream psOut; public static int BYTES_PER_LINE = 4; public BinCat() { this(System.in,System.out); } public BinCat(InputStream in, OutputStream out) { brIn = new BufferedInputStream(in); if (out instanceof PrintStream) psOut = (PrintStream)out; else psOut = new PrintStream(out); } public void doit() { int ch, cv, bit, cnt; try { for(cnt = 0, ch = brIn.read(); ch >= 0; ch = brIn.read()) { cv = ((int)ch & 0x00ff); for(bit = 7; bit >= 0; bit--) { if ((cv & (2 << bit)) > 0) psOut.print("1"); else psOut.print("0"); } cnt++; if ((cnt % BYTES_PER_LINE) == 0) psOut.println(""); } } catch (IOException e) { } return; } /** * Test main for BinCat */ public static void main(String args[]) { BinCat kitty; kitty = new BinCat(); kitty.doit(); System.exit(0); } }