1 32 33 package com.jeantessier.classreader; 34 35 public class BitFormat { 36 public static final int DEFAULT_MAX_LENGTH = 32; 37 public static final int DEFAULT_GROUP_SIZE = 8; 38 public static final char DEFAULT_GROUP_SEPARATOR = ' '; 39 40 private int maxLength; 41 private int groupSize; 42 private char groupSeparator; 43 44 public BitFormat() { 45 this(DEFAULT_MAX_LENGTH, DEFAULT_GROUP_SIZE, DEFAULT_GROUP_SEPARATOR); 46 } 47 48 public BitFormat(int maxLength) { 49 this(maxLength, DEFAULT_GROUP_SIZE, DEFAULT_GROUP_SEPARATOR); 50 } 51 52 public BitFormat(int maxLength, int groupSize) { 53 this(maxLength, groupSize, DEFAULT_GROUP_SEPARATOR); 54 } 55 56 public BitFormat(int maxLength, int groupSize, char groupSeparator) { 57 this.maxLength = maxLength; 58 this.groupSize = groupSize; 59 this.groupSeparator = groupSeparator; 60 } 61 62 public String format(int n) { 63 return format(Integer.toBinaryString(n).toCharArray()); 64 } 65 66 public String format(long n) { 67 return format(Long.toBinaryString(n).toCharArray()); 68 } 69 70 private String format(char[] binaryString) { 71 StringBuffer result = new StringBuffer (); 72 73 for (int i=0; i<maxLength; i++) { 74 if (((maxLength - i) % groupSize == 0) && i > 0) { 75 result.append(groupSeparator); 76 } 77 78 if (i < maxLength - binaryString.length) { 79 result.append('0'); 80 } else { 81 result.append(binaryString[binaryString.length - maxLength + i]); 82 } 83 } 84 85 return result.toString(); 86 } 87 } 88 | Popular Tags |