1 21 22 package org.apache.derbyTesting.unitTests.util; 23 24 25 55 public class BitUtil 56 { 57 67 public static byte[] set(byte[] bytes, int position) 68 { 69 if (position >= 0) 70 { 71 int bytepos = position >> 3; 72 if (bytepos < bytes.length) 73 { 74 int bitpos = 7 - (position % 8); 75 76 bytes[bytepos] |= (1 << bitpos); 77 return bytes; 78 } 79 } 80 throw new IndexOutOfBoundsException (Integer.toString(position)); 81 } 82 83 93 public static byte[] clear(byte[] bytes, int position) 94 { 95 if (position >= 0) 96 { 97 int bytepos = position >> 3; 98 if (bytepos < bytes.length) 99 { 100 int bitpos = 7 - (position % 8); 101 bytes[bytepos] &= ~(1 << bitpos); 102 return bytes; 103 } 104 } 105 106 throw new IndexOutOfBoundsException (Integer.toString(position)); 107 } 108 109 119 public static boolean get(byte[] bytes, int position) 120 { 121 if (position >= 0) 122 { 123 int bytepos = position >> 3; 124 if (bytepos < bytes.length) 125 { 126 int bitpos = 7 - (position % 8); 127 return ((bytes[bytepos] & (1 << bitpos)) != 0); 128 } 129 } 130 throw new IndexOutOfBoundsException (Integer.toString(position)); 131 } 132 133 private static char[] hex_table = { 134 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 135 'a', 'b', 'c', 'd', 'e', 'f' 136 }; 137 138 141 public static String hexDump(byte[] data) 142 { 143 byte byte_value; 144 145 146 StringBuffer str = new StringBuffer (data.length * 3); 147 148 str.append("Hex dump:\n"); 149 150 for (int i = 0; i < data.length; i += 16) 151 { 152 String offset = Integer.toHexString(i); 154 155 for (int offlen = offset.length(); offlen < 8; offlen++) 157 str.append("0"); 158 str.append(offset); 159 str.append(":"); 160 161 for (int j = 0; (j < 16) && ((i + j) < data.length); j++) 163 { 164 byte_value = data[i + j]; 165 166 if ((j % 2) == 0) 168 str.append(" "); 169 170 byte high_nibble = (byte) ((byte_value & 0xf0) >>> 4); 172 byte low_nibble = (byte) (byte_value & 0x0f); 173 174 str.append(hex_table[high_nibble]); 175 str.append(hex_table[low_nibble]); 176 } 177 178 str.append(" "); 180 181 for (int j = 0; (j < 16) && ((i + j) < data.length); j++) 182 { 183 char char_value = (char) data[i + j]; 184 185 if (Character.isLetterOrDigit(char_value)) 187 str.append(String.valueOf(char_value)); 188 else 189 str.append("."); 190 } 191 192 str.append("\n"); 194 } 195 return(str.toString()); 196 197 } 198 } 199 | Popular Tags |