当前位置: 代码迷 >> Java相关 >> 字符串转定长数组解决方法
  详细解决方案

字符串转定长数组解决方法

热度:6275   发布时间:2013-02-25 21:49:32.0
字符串转定长数组
String a ="2dsad132321321321";
byte[] b = byte[100];
我现在想把字符串a转定长的byte数组b,不够的位用0x00补齐;
该怎么做,求大虾指教

------解决方案--------------------------------------------------------
提醒你注意 结贴给分哈

我下面实现了转换,但是要求是字符串转换为字节数组不会超过100位,如果超过了我没处理
Java code
public class String2byteDemo {     public static void main(String[] args) {        String a ="2dsad132321321321";        byte[] b = new byte[100];        byte[] temp=a.getBytes();        int length=temp.length;        if(length<=100){            for(int i=0;i<100;i++){                if(i<length){                    b[i]=temp[i];                }else{                    b[i]=0x00;                }            }        }        for(byte i:b){            System.out.print(i+",");        }    }}
------解决方案--------------------------------------------------------
public static void main(String[] args) {
String a="2afsabsdfgsdgcdbdfhrergfd1234fdsgsgsg";
byte[] b=new byte[100];
int i;
for(i=0;i<a.length();i++){
a.getBytes(i, i+1, b, i);
}
while(i<100){
b[i]=0x00;
i++;
}
System.out.println(Arrays.toString(b));
}
  相关解决方案