1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.googlecode.android_scripting; 18 19 public class ConvertUtils { 20 /** 21 * Converts a String of comma separated bytes to a byte array 22 * 23 * @param value The value to convert 24 * @return the byte array 25 */ convertStringToByteArray(String value)26 public static byte[] convertStringToByteArray(String value) { 27 if (value.equals("")) { 28 return new byte[0]; 29 } 30 String[] parseString = value.split(","); 31 byte[] byteArray = new byte[parseString.length]; 32 if (byteArray.length > 0) { 33 for (int i = 0; i < parseString.length; i++) { 34 int val = Integer.valueOf(parseString[i].trim()); 35 if (val < 0 || val > 255) 36 throw new java.lang.NumberFormatException("Val must be between 0 and 255"); 37 byteArray[i] = (byte)val; 38 } 39 } 40 return byteArray; 41 } 42 43 /** 44 * Converts a byte array to a comma separated String 45 * 46 * @param byteArray 47 * @return comma separated string of bytes 48 */ convertByteArrayToString(byte[] byteArray)49 public static String convertByteArrayToString(byte[] byteArray) { 50 String ret = ""; 51 if (byteArray != null) { 52 for (int i = 0; i < byteArray.length; i++) { 53 if ((i + 1) != byteArray.length) { 54 ret = ret + Integer.valueOf((byteArray[i]&0xFF)) + ","; 55 } 56 else { 57 ret = ret + Integer.valueOf((byteArray[i]&0xFF)); 58 } 59 } 60 } 61 return ret; 62 } 63 64 } 65