Convert String to String Hex - Java java.lang

Java examples for java.lang:Hex

Description

Convert String to String Hex

Demo Code


import java.math.BigDecimal;
import java.security.MessageDigest;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        String s = "java2s.com";
        System.out.println(toStringHex(s));
    }//from ww  w.  j  a  va  2  s .  c o m
    private static Logger logger = Logger.getLogger(AlgorithmUtils.class);
    
    public static String toStringHex(String s) {
        byte[] byStr = new byte[s.length() / 2];
        for (int i = 0; i < byStr.length; i++) {
            try {
                byStr[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        try {
            s = new String(byStr, "utf-8");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }
}

Related Tutorials