Skip to Content
avatar image
-1
Former Member

how to convert a character string to a hex string

Hi all, I am a Java Programmer, and I have two functions:

1. covert a character string to a hex string

2. covert a hex string to a character string

I can implement these functions in Java, anyone can help me implement these functions in ABAP. below is my Java code:

import java.io.ByteArrayOutputStream;


public class Main {
	private static String hexString = "0123456789ABCDEF";
	/**
	 * encoding a character string to hex String
	 * @param str
	 * @return
	 */
	public static String encode(String str) {
		byte[] bytes = str.getBytes();
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}
	/**
	 * decoding a hex string to character string
	 * @param bytes
	 * @return
	 */
	public static String decode(String bytes) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
		for (int i = 0; i < bytes.length(); i += 2)
			baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
		return new String(baos.toByteArray());
	}
	public static void main(String[] args) {
		String ch = "寄售差额调整";
		System.out.println("‘寄售差额调整’ in Hex String:"+Main.encode(ch));
		System.out.println("‘BCC4CADBB2EEB6EEB5F7D5FB’ in Chinese charater String::"+Main.decode(Main.encode(ch)));


	}
}

Thanks in advance.

Add comment
10|10000 characters needed characters exceeded

  • Get RSS Feed

4 Answers

  • Best Answer
    Nov 27, 2016 at 10:59 AM

    There's an implicit data type conversion between byte-like strings and character-like strings (cf ABAP documentation: Conversion Rules for Elementary Data Types):

    DATA hex TYPE xstring.
    DATA chars TYPE string.
    chars = 'EFBBBF'. "only uppercase
    hex = chars.
    chars = hex.
    Add comment
    10|10000 characters needed characters exceeded

  • avatar image
    Former Member
    Nov 28, 2016 at 11:58 AM
    -1
    Add comment
    10|10000 characters needed characters exceeded

  • avatar image
    Former Member
    Nov 28, 2016 at 12:24 PM
    -1

    Hi,

    Please use below code.

    * READ TABLE i_data into w_data INDEX 1.
    ** move w_data-line to v_xml.
    CALL FUNCTION 'HR_KR_STRING_TO_XSTRING'
    EXPORTING
    * CODEPAGE_TO = '8500'
    unicode_string = l_xml_table
    * OUT_LEN =
    IMPORTING
    xstring_stream = v_xml.
    * EXCEPTIONS
    * INVALID_CODEPAGE = 1
    * INVALID_STRING = 2
    * OTHERS = 3
    * .

    Thanks,

    Bala

    Add comment
    10|10000 characters needed characters exceeded

  • Nov 28, 2016 at 06:30 PM

    If a codepage conversion is needed, use CL_ABAP_CODEPAGE, Methods CONVERT_TO and CONVERT_FROM.

    Otherwise, as Sandra said ...

    Add comment
    10|10000 characters needed characters exceeded