Strings { public static ByteSource parseHex(String string) { if (!string.startsWith("0x")) { throw new RuntimeException("not a hex string"); } byte[] ret = new byte[ (string.length()-2) / 2 ]; int resultIndex = 0; for (int strIndex=2; strIndex < string.length(); ++strIndex) { final char strChar = string.charAt(strIndex); if (!Character.isWhitespace(strChar)) { int high = (Character.digit(strChar, 16)) << 4; char lowChar = string.charAt(++strIndex); int low = (Character.digit(lowChar, 16)); ret[resultIndex++] = (byte) (low + high); } } return new WrappingByteSource().wrap(ret, 0, resultIndex); }  static List<String> entriesToString(Map<?, ?> map); static String nl(); static String join(Collection<?> strings); static String join(Object... strings); static String join(Collection<?> strings, String delimiter); static String repeatString(String str, int count); static List<String> stringAndSort(Collection<?> inputs); static List<String> stringAndSort(Map<?,?> inputs); static List<String> dumpResource(Class<?> forClass, String path); static List<String> dumpURLs(Enumeration<URL> urls); @SuppressWarnings("unused") // primarily useful in debuggers static String[] dumpException(Throwable t); static String toOctal(byte[] bytes); static String hex(byte[] bytes); static String hex(ByteSource byteSource); static String hex(byte[] bytes, int start, int length); static ByteSource parseHexWithout0x(String st); static ByteSource parseHex(String string); static List<String> readStream(InputStream is); static void readStreamTo(InputStream is, Appendable out, boolean keepNL); static String toString(Multimap<T,?> map); static String stripr(String input, String suffix); static List<String> dumpFile(File file); static String dumpFileToString(File file); static List<String> mapToString(Collection<?> collection); static boolean equalCharsets(Charset one, String two); static String formatMD5(byte[] md5, boolean toLowerCase); static String truncateIfNecessary(String str, int codePointCount); static String toBase64(byte[] bytes); static String toBase64(byte[] bytes, int offset, int length); static byte[] fromBase64(CharSequence cs); static String[] parseQualifiedName(String arg, int maxParts); static String quotedIdent(String s, char quote, boolean force); static String escapeIdentifier(String s); static final String NL; }
@Test public void testStringToBytes() { ByteSource actual = Strings.parseHex("0xBEEFCAFE"); int[] expectedInts = { 190, 239, 202, 254 }; byte[] expected = new byte[expectedInts.length]; for (int i=0; i < expected.length; ++i) { expected[i] = (byte)expectedInts[i]; } assertEquals("bytes", new WrappingByteSource(expected), actual); }
@Test public void withSpace() { ByteSource actual = Strings.parseHex("0x BE EFCA FE"); int[] expectedInts = { 190, 239, 202, 254 }; byte[] expected = new byte[expectedInts.length]; for (int i=0; i < expected.length; ++i) { expected[i] = (byte)expectedInts[i]; } assertEquals("bytes", new WrappingByteSource(expected), actual); }