java byte 与int的互相转换
来源:互联网 发布:淘宝店家等级怎么看 编辑:程序博客网 时间:2024/05/21 13:03
1.byte uses 1 byte while int uses4 bytes.
2. integer literals like "45" are of byte int not byte.
If you want a literal to be a byte, you have to
cast it: "(byte)45".
3. When values are promoted as part of an expression
or as parameters to a method call, they may be
promoted to int, but never to byte.
4. Many parts of the Java language used int, but none
of them use byte. For example, the length of an
array is an int.
/**
* Convert an int to a byte array
*
* @param value int
* @return byte[]
*/
public static byte[] intToByteArray(int value) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
int offset = (b.length - 1 - i) * 8;
b[i] = (byte) ((value >>> offset) & 0xFF);
}
return b;
}
/**
* Convert the byte array to an int starting from the given offset.
*
* @param b The byte array
* @param offset The array offset,如果byte数组长度就是4,则该值为0
* @return The integer
*/
public static int byteArrayToInt(byte[] b, int offset) {
int value = 0;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i + offset] & 0x000000FF) << shift;
}
return value;
}
2. integer literals like "45" are of byte int not byte.
If you want a literal to be a byte, you have to
cast it: "(byte)45".
3. When values are promoted as part of an expression
or as parameters to a method call, they may be
promoted to int, but never to byte.
4. Many parts of the Java language used int, but none
of them use byte. For example, the length of an
array is an int.
/**
* Convert an int to a byte array
*
* @param value int
* @return byte[]
*/
public static byte[] intToByteArray(int value) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
int offset = (b.length - 1 - i) * 8;
b[i] = (byte) ((value >>> offset) & 0xFF);
}
return b;
}
/**
* Convert the byte array to an int starting from the given offset.
*
* @param b The byte array
* @param offset The array offset,如果byte数组长度就是4,则该值为0
* @return The integer
*/
public static int byteArrayToInt(byte[] b, int offset) {
int value = 0;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i + offset] & 0x000000FF) << shift;
}
return value;
}
- java byte 与int的互相转换
- java byte[] 与int float long 等的互相转换
- Java 将byte[] 与int类型互相转换
- c语言 int与byte[]互相转换
- int byte互相转换
- java int与byte【】之间的转换
- java int 与 byte转换
- java类对象与byte数组的互相转换
- java 里byte int互相转换为什么要与0xff
- Int与Byte的转换
- Socket编程int与byte array之间互相转换
- java中byte(byte []), int的转换
- Java 图片与byte数组互相转换
- <Java>byte与short互相转换
- Java 图片与byte数组互相转换
- java 中byte 与bit 互相转换
- Java 图片与byte数组互相转换
- java byte转int 互相转换原理详解
- 虚拟机上搭建Ubuntu系统步骤
- Webservice的认识小结
- 从零认识tomcat,构建一机多实例tomcat集群
- 将byte[]转化十六进制的字符串问题剖析
- 解释一下“堆栈”为什么连起来读
- java byte 与int的互相转换
- GCC 中的编译器堆栈保护技术
- 创业公司为什么应该写博客?读后感
- lucene资源列表
- 升级到Visual C++ 2010的三纪律八注意
- 如何选择电压、电流型的运放
- Subsets II
- 初习C++点滴摘录之编程的一些规则与建议(1)
- oracle 10g 11g 使用dos命令启动服务