You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ByteUtil.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. /*
  2. Copyright (c) 2005 Health Market Science, Inc.
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  14. USA
  15. You can contact Health Market Science at info@healthmarketscience.com
  16. or at the following address:
  17. Health Market Science
  18. 2700 Horizon Drive
  19. Suite 200
  20. King of Prussia, PA 19406
  21. */
  22. package com.healthmarketscience.jackcess;
  23. import java.io.FileWriter;
  24. import java.io.IOException;
  25. import java.io.PrintWriter;
  26. import java.nio.ByteBuffer;
  27. import java.nio.ByteOrder;
  28. import java.util.Arrays;
  29. /**
  30. * Byte manipulation and display utilities
  31. * @author Tim McCune
  32. */
  33. public final class ByteUtil {
  34. private static final String[] HEX_CHARS = new String[] {
  35. "0", "1", "2", "3", "4", "5", "6", "7",
  36. "8", "9", "A", "B", "C", "D", "E", "F"};
  37. private ByteUtil() {}
  38. /**
  39. * Put an integer into the given buffer at the given offset as a 3-byte
  40. * integer.
  41. * @param buffer buffer into which to insert the int
  42. * @param val Int to convert
  43. */
  44. public static void put3ByteInt(ByteBuffer buffer, int val)
  45. {
  46. put3ByteInt(buffer, val, buffer.order());
  47. }
  48. /**
  49. * Put an integer into the given buffer at the given offset as a 3-byte
  50. * integer.
  51. * @param buffer buffer into which to insert the int
  52. * @param val Int to convert
  53. * @param order the order to insert the bytes of the int
  54. */
  55. public static void put3ByteInt(ByteBuffer buffer, int val, ByteOrder order)
  56. {
  57. int pos = buffer.position();
  58. put3ByteInt(buffer, val, pos, order);
  59. buffer.position(pos + 3);
  60. }
  61. /**
  62. * Put an integer into the given buffer at the given offset as a 3-byte
  63. * integer.
  64. * @param buffer buffer into which to insert the int
  65. * @param val Int to convert
  66. * @param offset offset at which to insert the int
  67. * @param order the order to insert the bytes of the int
  68. */
  69. public static void put3ByteInt(ByteBuffer buffer, int val, int offset,
  70. ByteOrder order) {
  71. int offInc = 1;
  72. if(order == ByteOrder.BIG_ENDIAN) {
  73. offInc = -1;
  74. offset += 2;
  75. }
  76. buffer.put(offset, (byte) (val & 0xFF));
  77. buffer.put(offset + (1 * offInc), (byte) ((val >>> 8) & 0xFF));
  78. buffer.put(offset + (2 * offInc), (byte) ((val >>> 16) & 0xFF));
  79. }
  80. /**
  81. * Read a 3 byte int from a buffer
  82. * @param buffer Buffer containing the bytes
  83. * @return The int
  84. */
  85. public static int get3ByteInt(ByteBuffer buffer) {
  86. return get3ByteInt(buffer, buffer.order());
  87. }
  88. /**
  89. * Read a 3 byte int from a buffer
  90. * @param buffer Buffer containing the bytes
  91. * @param order the order of the bytes of the int
  92. * @return The int
  93. */
  94. public static int get3ByteInt(ByteBuffer buffer, ByteOrder order) {
  95. int pos = buffer.position();
  96. int rtn = get3ByteInt(buffer, pos, order);
  97. buffer.position(pos + 3);
  98. return rtn;
  99. }
  100. /**
  101. * Read a 3 byte int from a buffer
  102. * @param buffer Buffer containing the bytes
  103. * @param offset Offset at which to start reading the int
  104. * @return The int
  105. */
  106. public static int get3ByteInt(ByteBuffer buffer, int offset) {
  107. return get3ByteInt(buffer, offset, buffer.order());
  108. }
  109. /**
  110. * Read a 3 byte int from a buffer
  111. * @param buffer Buffer containing the bytes
  112. * @param offset Offset at which to start reading the int
  113. * @param order the order of the bytes of the int
  114. * @return The int
  115. */
  116. public static int get3ByteInt(ByteBuffer buffer, int offset,
  117. ByteOrder order) {
  118. int offInc = 1;
  119. if(order == ByteOrder.BIG_ENDIAN) {
  120. offInc = -1;
  121. offset += 2;
  122. }
  123. int rtn = getUnsignedByte(buffer, offset);
  124. rtn += (getUnsignedByte(buffer, offset + (1 * offInc)) << 8);
  125. rtn += (getUnsignedByte(buffer, offset + (2 * offInc)) << 16);
  126. return rtn;
  127. }
  128. /**
  129. * Read an unsigned byte from a buffer
  130. * @param buffer Buffer containing the bytes
  131. * @return The unsigned byte as an int
  132. */
  133. public static int getUnsignedByte(ByteBuffer buffer) {
  134. int pos = buffer.position();
  135. int rtn = getUnsignedByte(buffer, pos);
  136. buffer.position(pos + 1);
  137. return rtn;
  138. }
  139. /**
  140. * Read an unsigned byte from a buffer
  141. * @param buffer Buffer containing the bytes
  142. * @param offset Offset at which to read the byte
  143. * @return The unsigned byte as an int
  144. */
  145. public static int getUnsignedByte(ByteBuffer buffer, int offset) {
  146. return asUnsignedByte(buffer.get(offset));
  147. }
  148. /**
  149. * Read an unsigned short from a buffer
  150. * @param buffer Buffer containing the short
  151. * @return The unsigned short as an int
  152. */
  153. public static int getUnsignedShort(ByteBuffer buffer) {
  154. int pos = buffer.position();
  155. int rtn = getUnsignedShort(buffer, pos);
  156. buffer.position(pos + 2);
  157. return rtn;
  158. }
  159. /**
  160. * Read an unsigned short from a buffer
  161. * @param buffer Buffer containing the short
  162. * @param offset Offset at which to read the short
  163. * @return The unsigned short as an int
  164. */
  165. public static int getUnsignedShort(ByteBuffer buffer, int offset) {
  166. return asUnsignedShort(buffer.getShort(offset));
  167. }
  168. /**
  169. * @param buffer Buffer containing the bytes
  170. * @param order the order of the bytes of the int
  171. * @return an int from the current position in the given buffer, read using
  172. * the given ByteOrder
  173. */
  174. public static int getInt(ByteBuffer buffer, ByteOrder order) {
  175. int offset = buffer.position();
  176. int rtn = getInt(buffer, offset, order);
  177. buffer.position(offset + 4);
  178. return rtn;
  179. }
  180. /**
  181. * @param buffer Buffer containing the bytes
  182. * @param offset Offset at which to start reading the int
  183. * @param order the order of the bytes of the int
  184. * @return an int from the given position in the given buffer, read using
  185. * the given ByteOrder
  186. */
  187. public static int getInt(ByteBuffer buffer, int offset, ByteOrder order) {
  188. ByteOrder origOrder = buffer.order();
  189. try {
  190. return buffer.order(order).getInt(offset);
  191. } finally {
  192. buffer.order(origOrder);
  193. }
  194. }
  195. /**
  196. * Writes an int at the current position in the given buffer, using the
  197. * given ByteOrder
  198. * @param buffer buffer into which to insert the int
  199. * @param val Int to insert
  200. * @param order the order to insert the bytes of the int
  201. */
  202. public static void putInt(ByteBuffer buffer, int val, ByteOrder order) {
  203. int offset = buffer.position();
  204. putInt(buffer, val, offset, order);
  205. buffer.position(offset + 4);
  206. }
  207. /**
  208. * Writes an int at the given position in the given buffer, using the
  209. * given ByteOrder
  210. * @param buffer buffer into which to insert the int
  211. * @param val Int to insert
  212. * @param offset offset at which to insert the int
  213. * @param order the order to insert the bytes of the int
  214. */
  215. public static void putInt(ByteBuffer buffer, int val, int offset,
  216. ByteOrder order)
  217. {
  218. ByteOrder origOrder = buffer.order();
  219. try {
  220. buffer.order(order).putInt(offset, val);
  221. } finally {
  222. buffer.order(origOrder);
  223. }
  224. }
  225. /**
  226. * Sets all bits in the given remaining byte range to 0.
  227. */
  228. public static void clearRemaining(ByteBuffer buffer)
  229. {
  230. if(!buffer.hasRemaining()) {
  231. return;
  232. }
  233. int pos = buffer.position();
  234. clearRange(buffer, pos, pos + buffer.remaining());
  235. }
  236. /**
  237. * Sets all bits in the given byte range to 0.
  238. */
  239. public static void clearRange(ByteBuffer buffer, int start,
  240. int end)
  241. {
  242. putRange(buffer, start, end, (byte)0x00);
  243. }
  244. /**
  245. * Sets all bits in the given byte range to 1.
  246. */
  247. public static void fillRange(ByteBuffer buffer, int start,
  248. int end)
  249. {
  250. putRange(buffer, start, end, (byte)0xff);
  251. }
  252. /**
  253. * Sets all bytes in the given byte range to the given byte value.
  254. */
  255. public static void putRange(ByteBuffer buffer, int start,
  256. int end, byte b)
  257. {
  258. for(int i = start; i < end; ++i) {
  259. buffer.put(i, b);
  260. }
  261. }
  262. /**
  263. * Matches a pattern of bytes against the given buffer starting at the given
  264. * offset.
  265. */
  266. public static boolean matchesRange(ByteBuffer buffer, int start,
  267. byte[] pattern)
  268. {
  269. for(int i = 0; i < pattern.length; ++i) {
  270. if(pattern[i] != buffer.get(start + i)) {
  271. return false;
  272. }
  273. }
  274. return true;
  275. }
  276. /**
  277. * Searches for a pattern of bytes in the given buffer starting at the
  278. * given offset.
  279. * @return the offset of the pattern if a match is found, -1 otherwise
  280. */
  281. public static int findRange(ByteBuffer buffer, int start, byte[] pattern)
  282. {
  283. byte firstByte = pattern[0];
  284. int limit = buffer.limit() - pattern.length;
  285. for(int i = start; i < limit; ++i) {
  286. if((firstByte == buffer.get(i)) && matchesRange(buffer, i, pattern)) {
  287. return i;
  288. }
  289. }
  290. return -1;
  291. }
  292. /**
  293. * Convert a byte buffer to a hexadecimal string for display
  294. * @param buffer Buffer to display, starting at offset 0
  295. * @param size Number of bytes to read from the buffer
  296. * @return The display String
  297. */
  298. public static String toHexString(ByteBuffer buffer, int size) {
  299. return toHexString(buffer, 0, size);
  300. }
  301. /**
  302. * Convert a byte array to a hexadecimal string for display
  303. * @param array byte array to display, starting at offset 0
  304. * @return The display String
  305. */
  306. public static String toHexString(byte[] array) {
  307. return toHexString(ByteBuffer.wrap(array), 0, array.length);
  308. }
  309. /**
  310. * Convert a byte buffer to a hexadecimal string for display
  311. * @param buffer Buffer to display, starting at offset 0
  312. * @param offset Offset at which to start reading the buffer
  313. * @param size Number of bytes to read from the buffer
  314. * @return The display String
  315. */
  316. public static String toHexString(ByteBuffer buffer, int offset, int size) {
  317. return toHexString(buffer, offset, size, true);
  318. }
  319. /**
  320. * Convert a byte buffer to a hexadecimal string for display
  321. * @param buffer Buffer to display, starting at offset 0
  322. * @param offset Offset at which to start reading the buffer
  323. * @param size Number of bytes to read from the buffer
  324. * @param formatted flag indicating if formatting is required
  325. * @return The display String
  326. */
  327. public static String toHexString(ByteBuffer buffer,
  328. int offset, int size, boolean formatted) {
  329. StringBuilder rtn = new StringBuilder();
  330. int position = buffer.position();
  331. buffer.position(offset);
  332. for (int i = 0; i < size; i++) {
  333. byte b = buffer.get();
  334. byte h = (byte) (b & 0xF0);
  335. h = (byte) (h >>> 4);
  336. h = (byte) (h & 0x0F);
  337. rtn.append(HEX_CHARS[h]);
  338. h = (byte) (b & 0x0F);
  339. rtn.append(HEX_CHARS[h]);
  340. if (formatted == true)
  341. {
  342. rtn.append(" ");
  343. if ((i + 1) % 4 == 0) {
  344. rtn.append(" ");
  345. }
  346. if ((i + 1) % 24 == 0) {
  347. rtn.append("\n");
  348. }
  349. }
  350. }
  351. buffer.position(position);
  352. return rtn.toString();
  353. }
  354. /**
  355. * Writes a sequence of hexidecimal values into the given buffer, where
  356. * every two characters represent one byte value.
  357. */
  358. public static void writeHexString(ByteBuffer buffer,
  359. String hexStr)
  360. throws IOException
  361. {
  362. char[] hexChars = hexStr.toCharArray();
  363. if((hexChars.length % 2) != 0) {
  364. throw new IOException("Hex string length must be even");
  365. }
  366. for(int i = 0; i < hexChars.length; i += 2) {
  367. String tmpStr = new String(hexChars, i, 2);
  368. buffer.put((byte)Long.parseLong(tmpStr, 16));
  369. }
  370. }
  371. /**
  372. * Writes a chunk of data to a file in pretty printed hexidecimal.
  373. */
  374. public static void toHexFile(
  375. String fileName,
  376. ByteBuffer buffer,
  377. int offset, int size)
  378. throws IOException
  379. {
  380. PrintWriter writer = new PrintWriter(
  381. new FileWriter(fileName));
  382. try {
  383. writer.println(toHexString(buffer, offset, size));
  384. } finally {
  385. writer.close();
  386. }
  387. }
  388. /**
  389. * @return the byte value converted to an unsigned int value
  390. */
  391. public static int asUnsignedByte(byte b) {
  392. return b & 0xFF;
  393. }
  394. /**
  395. * @return the short value converted to an unsigned int value
  396. */
  397. public static int asUnsignedShort(short s) {
  398. return s & 0xFFFF;
  399. }
  400. /**
  401. * Swaps the 4 bytes (changes endianness) of the bytes at the given offset.
  402. *
  403. * @param bytes buffer containing bytes to swap
  404. * @param offset offset of the first byte of the bytes to swap
  405. */
  406. public static void swap4Bytes(byte[] bytes, int offset)
  407. {
  408. byte b = bytes[offset + 0];
  409. bytes[offset + 0] = bytes[offset + 3];
  410. bytes[offset + 3] = b;
  411. b = bytes[offset + 1];
  412. bytes[offset + 1] = bytes[offset + 2];
  413. bytes[offset + 2] = b;
  414. }
  415. /**
  416. * Swaps the 2 bytes (changes endianness) of the bytes at the given offset.
  417. *
  418. * @param bytes buffer containing bytes to swap
  419. * @param offset offset of the first byte of the bytes to swap
  420. */
  421. public static void swap2Bytes(byte[] bytes, int offset)
  422. {
  423. byte b = bytes[offset + 0];
  424. bytes[offset + 0] = bytes[offset + 1];
  425. bytes[offset + 1] = b;
  426. }
  427. /**
  428. * Moves the position of the given buffer the given count from the current
  429. * position.
  430. * @return the new buffer position
  431. */
  432. public static int forward(ByteBuffer buffer, int count)
  433. {
  434. int newPos = buffer.position() + count;
  435. buffer.position(newPos);
  436. return newPos;
  437. }
  438. /**
  439. * Utility byte stream similar to ByteArrayOutputStream but with extended
  440. * accessibility to the bytes.
  441. */
  442. public static class ByteStream
  443. {
  444. private byte[] _bytes;
  445. private int _length;
  446. private int _lastLength;
  447. public ByteStream() {
  448. this(32);
  449. }
  450. public ByteStream(int capacity) {
  451. _bytes = new byte[capacity];
  452. }
  453. public int getLength() {
  454. return _length;
  455. }
  456. public byte[] getBytes() {
  457. return _bytes;
  458. }
  459. protected void ensureNewCapacity(int numBytes) {
  460. int newLength = _length + numBytes;
  461. if(newLength > _bytes.length) {
  462. byte[] temp = new byte[newLength * 2];
  463. System.arraycopy(_bytes, 0, temp, 0, _length);
  464. _bytes = temp;
  465. }
  466. }
  467. public void write(int b) {
  468. ensureNewCapacity(1);
  469. _bytes[_length++] = (byte)b;
  470. }
  471. public void write(byte[] b) {
  472. write(b, 0, b.length);
  473. }
  474. public void write(byte[] b, int offset, int length) {
  475. ensureNewCapacity(length);
  476. System.arraycopy(b, offset, _bytes, _length, length);
  477. _length += length;
  478. }
  479. public byte get(int offset) {
  480. return _bytes[offset];
  481. }
  482. public void set(int offset, byte b) {
  483. _bytes[offset] = b;
  484. }
  485. public void writeFill(int length, byte b) {
  486. ensureNewCapacity(length);
  487. int oldLength = _length;
  488. _length += length;
  489. Arrays.fill(_bytes, oldLength, _length, b);
  490. }
  491. public void writeTo(ByteStream out) {
  492. out.write(_bytes, 0, _length);
  493. }
  494. public byte[] toByteArray() {
  495. byte[] result = null;
  496. if(_length == _bytes.length) {
  497. result = _bytes;
  498. _bytes = null;
  499. } else {
  500. result = new byte[_length];
  501. System.arraycopy(_bytes, 0, result, 0, _length);
  502. if(_lastLength == _length) {
  503. // if we get the same result length bytes twice in a row, clear the
  504. // _bytes so that the next _bytes will be _lastLength
  505. _bytes = null;
  506. }
  507. }
  508. // save result length so we can potentially get the right length of the
  509. // next byte[] in reset()
  510. _lastLength = _length;
  511. return result;
  512. }
  513. public void reset() {
  514. _length = 0;
  515. if(_bytes == null) {
  516. _bytes = new byte[_lastLength];
  517. }
  518. }
  519. public void trimTrailing(byte minTrimCode, byte maxTrimCode)
  520. {
  521. int minTrim = ByteUtil.asUnsignedByte(minTrimCode);
  522. int maxTrim = ByteUtil.asUnsignedByte(maxTrimCode);
  523. int idx = _length - 1;
  524. while(idx >= 0) {
  525. int val = asUnsignedByte(get(idx));
  526. if((val >= minTrim) && (val <= maxTrim)) {
  527. --idx;
  528. } else {
  529. break;
  530. }
  531. }
  532. _length = idx + 1;
  533. }
  534. }
  535. }