java中进制数_(四)Java中的进制

1、Java中的数据类型

由于Java通常用来处理高层,因此平时开发中“进制转换”和“位运算”用的不多,但在跨平台中使用频繁,如文件读写、数据通信等。

1.基本数据类型

int类型 |

----|------|----

byte | short | int| long

8bit | 16bit |32bit| 64bit

float类型 |

----|------|----

单精度 | 双精度

32bit float | 64bit double

boolean类型:true、false

char类型:Unicode字符,16位

2.对应的包装类

Integer| Byte |Short | Long | Float | Boolean | Character

----|------|----

int| byte | short | long| float| boolean| char

2、数据类型转化为字节

例:

int a = 8143;//8143是int类型,32bit,也就是4个字节。

//转为二进制是(00000000 00000000 00011111 11001111)

第一个(低端)字节:(8143>>0*8)&0xff=(11001111)= 207(有符号为-49)

//即8143右移0x8个二进制位,再&上0xff(11111111),可求得从右边数的第一个字节。

第二个(低端)字节:(8143>>1*8)&0xff=(00011111)= 31

//即8143右移1x8个二进制位,再&上0xff(11111111),可求得从右边数的第二个字节。

第三个(低端)字节:(8143>>2*8)&0xff=(00000000)= 0

//即8143右移2x8个二进制位,再&上0xff(11111111),可求得从右边数的第三个字节。

第四个(低端)字节:(8143>>3*8)&0xff=(00000000)= 0

//即8143右移3x8个二进制位,再&上0xff(11111111),可求得从右边数的第四个字节。

这里引入一个概念:

小端法(Little-Endian):

低位字节排放在内存的低地址端即该值的起始地址,高位字节排放在内存的高地址端。

大端法(Big-Endian):

高位字节排放在内存的低地址端即该值的起始地址,低位字节排放在内存的高地址端。

上述例子中的8143采取的就是小端法,更详细的内容可以参考大端小端格式详解

3、字符串转化为字节

字符串→字节数组

String s;

byte[ ] bs = s.getBytes( ) ;

字节数组→字符串

byte[ ] bs = new byte[int];

String s = new String(bs);

//或需要指定编码方式,例如“gb2312”等

String s = new String(bs,encode)

4、代码示例

public class Convert {

//int转为byte[]

public static byte[] int2Bytes(int num){

byte[] arr = new byte[4];

arr[0] =(byte)((int)(num>>0*8) & 0xff);

arr[1] =(byte)((int)(num>>1*8) & 0xff);

arr[2] =(byte)((int)(num>>2*8) & 0xff);

arr[3] =(byte)((int)(num>>3*8) & 0xff);

return arr;

}

//int转为byte[]可简化为

public static byte[] int2Bytes(int num){

byte[] arr = new byte[4];

for(int i = 0;i

arr[i]=(byte)((int)(num>>i*8) & 0xff);

}

return arr;

}

//byte[]转为int

public static int bytes2Int(byte[] arr){

int num0 = (int)((arr[0] & 0xff)<<0*8);

int num1 = (int)((arr[1] & 0xff)<<1*8);

int num2 = (int)((arr[2] & 0xff)<<2*8);

int num3 = (int)((arr[3] & 0xff)<<3*8);

return num0+num1+num2+num3;

}

return result;

}

//byte[]转为int可简化为

public static int bytes2Int(byte[] arr){

int result = 0;

for(int i = 0;i

result += (arr[i] & 0xff)<

}

return result;

}

public static void main(String[] args){

byte[] arr = Convert.int2Bytes(8143);

System.out.println(arr[0]+","+arr[1]+","+arr[2]+","+arr[3]);

System.out.println(Convert.bytes2Int(arr));

//字符串转为字节数组

String describe = "测试字符串";

byte[] barr = describe.getBytes();

for(byte b: barr){

System.out.print(Integer.toHexString(b&0xff)+" ");

}

String des = new String(barr);

System.out.println(des);

}

}

版权声明:欢迎转载,欢迎扩散,但转载时请标明作者以及原文出处,谢谢合作! ↓↓↓

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值