Java Byte Array Create toBytesHexEscaped(final byte[] s, final int off, final int len)

Here you can find the source of toBytesHexEscaped(final byte[] s, final int off, final int len)

Description

to Bytes Hex Escaped

License

Open Source License

Declaration

private static byte[] toBytesHexEscaped(final byte[] s, final int off, final int len) 

Method Source Code

//package com.java2s;
/*//from www .  j ava 2  s  .  co m
 * The MIT License
 *
 * Copyright 2015 Karol Bucek
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

public class Main {
    private static byte[] toBytesHexEscaped(final byte[] s, final int off, final int len) {
        final byte[] out = new byte[(len - 2) / 2];
        for (int i = 0; i < out.length; i++) {
            final int j = off + (2 + i * 2);
            byte b1 = hexByte(s[j]);
            byte b2 = hexByte(s[j + 1]);
            out[i] = (byte) ((b1 << 4) | b2);
        }
        return out;
    }

    private static byte hexByte(final byte b) {
        // 0-9 == 48-57
        if (b <= 57)
            return (byte) (b - 48);

        // a-f == 97-102
        if (b >= 97)
            return (byte) (b - 97 + 10);

        // A-F == 65-70
        return (byte) (b - 65 + 10);
    }
}

Related

  1. toBytesFromHexStr(String hexStr)
  2. toBytesFromHexString(String digits)
  3. toBytesFromOct(String octSymbols)
  4. toBytesFromString(String s)
  5. toBytesFromUnicode(String s)
  6. toBytesInt32BE(int w)
  7. toBytesLittleEndian(long value, int cnt)
  8. toBytesOctalEscaped(final byte[] s, final int off, final int len)
  9. toBytesShortBE(short w)