Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!mx05.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: convert byte array to hex string using BigInteger Date: Thu, 20 Jun 2013 09:03:38 -0400 Organization: A noiseless patient Spider Lines: 37 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 20 Jun 2013 12:58:33 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="0d73d8cc209bff1c6395088b400d0605"; logging-data="23070"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18Z+A0p/kGaF9l3pEyZsAbQ" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20130509 Thunderbird/17.0.6 In-Reply-To: Cancel-Lock: sha1:dGRQPWfTYssgCW3JhHvEiITkvxk= Xref: csiph.com comp.lang.java.programmer:24483 On 6/20/2013 8:03 AM, Laura Schmidt wrote: > Hi, > > I try to convert a byte array to a hex string like this: > > private static String hex_encode (byte [] val) > { > BigInteger b = new BigInteger(val); > > String t = b.toString(16); > > return (t); > } > > For a long byte array it returns a "negative" hex string, i. e. starting > with a "-" sign. > > But I want just the bytes in the array converted to hex representation, > each one ranging from "00" to "FF". There should be no minus sign then. > > Can you help? // Untested: private static String hexEncode(byte[] val) { StringBuilder buff = new StringBuilder(2 * val.length); for (byte b : val) { buff.append("0123456789ABCDEF".charAt((b >> 4) & 0xF)); buff.append("0123456789ABCDEF".charAt(b & 0xF)); } return buff.toString(); } There are other ways, too. -- Eric Sosman esosman@comcast-dot-net.invalid