搞分在线等待帮组(关于数据类型转换)

patriot_cool 2003-03-18 02:39:16
请问怎样把一个string类型变成二进制数呢?谢谢你的帮组
...全文
27 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
bluesmile979 2003-03-18
  • 打赏
  • 举报
回复
自己写

String s = "abcdefgh";
byte[] b = s.getBytes();
int[] r = new int[ b.length * 8 ];
for ( int i = 0; i < b.length; i++ ){
int t = 128;
for ( int j = 0; j < 8; j++ ){
r[ i * 8 + j] = ( ( int ) b[ i ] & t ) == 0 ? 0 : 1;
t = t >> 1;
}
}

int num = r.length / 8;
char[] bb = new char[num];
for ( int i = 0; i < num; i++ ){
bb[ i ] = 0;
for ( int j = 0; j < 8; j++ ){
bb[ i ] = ( char ) ( bb[ i ] << 1 );
bb[ i ] = ( char ) ( bb[ i ] | r[ i * 8 + j ] );
}
}
hoxisoft 2003-03-18
  • 打赏
  • 举报
回复
//转过去

char temChr ;
int ascChr ;
int i ;
String ss = "" ;
String rtStr = "地从" ;
int length = rtStr.length() ;
for ( i = 0 ; i < length ; i++ )
{
temChr = rtStr.charAt( i ) ;
ascChr = temChr + 0 ;
ss = ss + "&#x" + Integer.toHexString( ascChr ) + ";" ;

//转回来

String sArray[] = ss.split(";");
byte bArray[] = new byte[2 * sArray.length];
for (i = 0 ; i < sArray.length; i++) {
try {
int tmp = Integer.parseInt(sArray[i].substring(3), 16);
System.out.println(">>>>>int value is " + sArray[i].substring(3));
bArray[i*2 + 1] = (byte)(tmp & 0xff);
bArray[i*2 ] = (byte)((tmp >> 8) & 0xff);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
System.out.println("convert to orginal String is " + new String(bArray));

patriot_cool 2003-03-18
  • 打赏
  • 举报
回复
还有,我如何得到的二进制转换成字符串呀?
patriot_cool 2003-03-18
  • 打赏
  • 举报
回复
但是我的字符串中不是数字呀,而是像“aaa”这种!
zxhong 2003-03-18
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/1432/1432875.xml?temp=.8989984
xiaoyoung 2003-03-18
  • 打赏
  • 举报
回复
什么意思,数字就是用二进制方式存在计算机里的呀?
你是不是要转换成二进制的字符串输出?

java.lang.Integer.toBinaryString( java.lang.Integer.valueOf( str ).intValue() );

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧