Page 1 of 1

convert data character string to java array

Posted: Tue Sep 01, 2015 2:19 am
by NikerCR
Every time I process algorithm computation, there is much data to be inputted.
How can I convert data character string to java array quickly ?
Such as "12345678" to 0x12, 0x34, 0x56, 0x78

Re: convert data character string to java array

Posted: Sat Sep 05, 2015 9:59 pm
by UNKNwYSHSA
You can write code for your needs.
Here's mine:

Code: Select all

# -*- coding:utf-8 -*-
import sys

def to_java_byte_array(input_string):
    while input_string.count(' ') != 0:
        input_string = input_string.replace(' ', '')
   
    if ((len(input_string) & 1) != 0) :
        print "The input string length is not multiply of 2, please check."
        return -1;
    java_byte_array = "";
    for index in range(0, len(input_string) >> 1):
        offset = index << 1
        java_byte_array += "0x%c%c, " %(input_string[offset], input_string[offset + 1])
    java_byte_array.strip(', ')
    print java_byte_array

if __name__ == "__main__":
    argv = sys.argv
    argc = len(argv)
    if argc < 2:
        print "Usage: ~ <input_string>"
        exit(-1)
   
    exit(to_java_byte_array(argv[1]))

This code can be modified for other requirements, java byte array, C byte array, etc.