Java XML Hex hexToBytes(final String s)

Here you can find the source of hexToBytes(final String s)

Description

Converts the passed hex string to a byte array

License

Apache License

Parameter

Parameter Description
s the hex string to convert

Return

the byte array or null if the hex string was null or empty

Declaration

public static byte[] hexToBytes(final String s) 

Method Source Code

//package com.java2s;
/**//  ww w . j a va  2 s.c  o m
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at
    
  http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
 */

import javax.xml.bind.DatatypeConverter;

public class Main {
    /**
     * Converts the passed hex string to a byte array
     * @param s the hex string to convert
     * @return the byte array or null if the hex string was null or empty
     */
    public static byte[] hexToBytes(final String s) {
        if (s == null || s.isEmpty()) {
            return null;
        }
        String id = s;
        if (id.length() % 2 > 0) {
            id = "0" + id;
        }
        return DatatypeConverter.parseHexBinary(id);
    }
}

Related

  1. hexOut(byte[] byteArray)
  2. hexOutSpaces(byte[] byteArray)
  3. hexStringToByteArray(String hex)
  4. hexStringToByteArray(String s)
  5. hexStringToBytes(String text)
  6. hexToString(String str)
  7. printHexBinary(byte[] in)
  8. printHexBinary(final byte[] deviceMessage)
  9. readHexString(ByteBuffer buf)