從字串中取一個字元作為數組元素
public class mainclass {
public static void main(string[] arg) {
string text = "to be or not to be"; // define a string
byte[] textarray = text.getbytes();
for(byte b: textarray){
system.out.println(b);
}
}
給資料增加值
class substringcons {
public static void main(string args[]) {
byte ascii[] = { 65, 66, 67, 68, 69, 70 };
string s1 = new string(ascii);
system.out.println(s1);
string s2 = new string(ascii, 2, 3);
system.out.println(s2);
}
}
轉換成位元組來一個十六進位字串
import java.io.unsupportedencodingexception;
/**
* format validation
*
* this class encodes/decodes hexadecimal data
* @author jeffrey rodriguez
* @version $id: hexbin.java 125124 2005-01-14 00:23:54z kkrouse $
*/
public class main {
static private final int baselength = 255;
static private final int lookuplength = 16;
static private byte [] hexnumbertable = new byte[baselength];
static private byte [] lookuphexalphabet = new byte[lookuplength];
static {
for (int i = 0; i<baselength; i++ ) {
hexnumbertable[i] = -1;
}
for ( int i = '9'; i >= '0'; i--) {
hexnumbertable[i] = (byte) (i-'0');
}
for ( int i = 'f'; i>= 'a'; i--) {
hexnumbertable[i] = (byte) ( i-'a' + 10 );
}
for ( int i = 'f'; i>= 'a'; i--) {
hexnumbertable[i] = (byte) ( i-'a' + 10 );
}
for(int i = 0; i<10; i++ )
lookuphexalphabet[i] = (byte) ('0'+i );
for(int i = 10; i<=15; i++ )
lookuphexalphabet[i] = (byte) ('a'+i -10);
}
/**
* converts bytes to a hex string
*/
static public string bytestostring(byte[] binarydata)
{
if (binarydata == null)
return null;
return new string(encode(binarydata));
}
/**
* array of byte to encode
*
* @param binarydata
* @return return encode binary array
*/
static public byte[] encode(byte[] binarydata) {
if (binarydata == null)
return null;
int lengthdata = binarydata.length;
int lengthencode = lengthdata * 2;
byte[] encodeddata = new byte[lengthencode];
for( int i = 0; i<lengthdata; i++ ){
encodeddata[i*2] = lookuphexalphabet[(binarydata[i] >> 4) & 0xf];
encodeddata[i*2+1] = lookuphexalphabet[ binarydata[i] & 0xf];
}
return encodeddata;
}
}