java基础数据的转换
来源:互联网 发布:逻辑推理软件 编辑:程序博客网 时间:2024/05/16 18:29
1,最近写socket网络通信项目遇见了byte数组需要转换为各种类型,和16进制字符串的互相转换,封装了一些简单的工具类,给大家分享分享
2,代码
/** * 16进制字符串转换为Byte数组 */ public static byte[] toByte(String hex) { if (hex == null) { return null; } try { return Hex.decodeHex(hex.toCharArray()); } catch (DecoderException e) { logger.warn("Hex string Decoder error!", e); return null; } } /** * byte数组转换成十六进制字符串 */ public static String toHex(byte[] command) { return new String(Hex.encodeHex(command)).toUpperCase(); } public static byte[] short2Byte(short a) { byte[] b = new byte[2]; b[0] = (byte) (a >> 8); b[1] = (byte) (a); return b; } public static short[] int2Short(int a) { short[] b = new short[2]; b[0] = (short) (a >> 16); b[1] = (short) (a); return b; } public static int short2Int(short[] uids) { return (((uids[0] & 0xffffffff) << 16) | (uids[1] & 0xffffffff)); } public static short byte2Short(byte[] b) { return (short) (((b[0] & 0xff) << 8) | (b[1] & 0xff)); } public static byte[] intToByte(int i) { byte[] bytes = new byte[4]; bytes[0] = (byte) ((i >> 24) & 0xFF); bytes[1] = (byte) ((i >> 16) & 0xFF); bytes[2] = (byte) ((i >> 8) & 0xFF); bytes[3] = (byte) (i & 0xFF); return bytes; } public static Integer byteToInt(byte[] bytes) { if (bytes == null || bytes.length != 4) { return null; } return (bytes[0] & 0xff) << 24 | (bytes[1] & 0xff) << 16 | (bytes[2] & 0xff) << 8 | (bytes[3] & 0xff); }
注意
Hex此类为阿帕奇的工具类,需要 org.apache.commons包
阅读全文
0 0
- java基础数据的转换
- Java的数据转换
- Java的数据转换
- Java的数据转换总结
- java数据之间的转换
- java语言基础(10)——类型强制转换时的数据溢出计算
- json数据与JAVA数据的转换
- json数据与JAVA数据的转换
- json数据与JAVA数据的转换
- json数据与JAVA数据的转换
- json数据和java数据的转换
- json数据与JAVA数据的转换
- son数据与JAVA数据的转换
- json数据与JAVA数据的转换
- Android基础 平面数据与父子关系的数据转换
- java基础--->基本数据类型之间的转换
- Java基础-数据类型及其之间的转换
- Java基础---数据类型的定义和转换
- JAVA不可变类(immutable)机制与String的不可变性
- Python 基础学习---读取json文件
- python切割图片以及转8位图
- 嵌入式程序员面试基本习题
- cocos2dx Texture、SpriteFrame、Sprite的区别
- java基础数据的转换
- FFmpeg 安装
- 剑指offer—旋转数组的最小数字
- Dubbo基本原理及rpc过程
- MFC 基于对话框的简单加法器
- java实现的FTP上传下载客户端
- VS C#工程【调用另外一个项目的类】
- win7 下git初级使用
- SVN:Previous operation has not finished; run 'cleanup' if it was interrupted