java byte转换_Java-byte转换

1 importorg.springframework.stereotype.Component;2 importorg.springframework.util.StringUtils;3

4 import java.io.*;5

6 /**

7 * byte和各种数据类型之间的转换8 *9 *@authorzy10 * @date 2020-07-15 17:3011 */

12 @Component13 public classByteUtil {14

15 /**

16 * 1、16进制转(字符串)byte17 *18 *@paramhexString 16进制字符串19 *@returnbyte20 */

21 public static byte[] hexStringToByte(String hexString) {22 //方法1

23 if(StringUtils.isEmpty(hexString)) {24 return null;25 }26 hexString =hexString.toUpperCase();27 int length = hexString.length() / 2;28 char[] hexChars =hexString.toCharArray();29 byte[] d = new byte[length];30 for (int i = 0; i < length; i++) {31 int pos = i * 2;32 d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));33 }34 returnd;35 //方法236 //hexString = hexString.replaceAll(" ", "");37 //int len = hexString.length();38 //byte[] bytes = new byte[len / 2];39 //for (int i = 0; i < len; i += 2) {40 // //两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节41 //bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character42 //.digit(hexString.charAt(i + 1), 16));43 //}44 //return bytes;45 //方法346 //hexString = hexString.replaceAll(" ", "");47 //final byte[] byteArray = new byte[hexString.length() / 2];48 //int k = 0;49 //for (int i = 0; i < byteArray.length; i++) {//因为是16进制,最多只会占用4位,转换成字节需要两个16进制的字符,高位在先50 //byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);51 //byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);52 //byteArray[i] = (byte) (high << 4 | low);53 //k += 2;54 //}55 //return byteArray;

56 }57

58 /**

59 * 2、char转byte60 *61 *@paramc 字符62 *@returnbyte63 */

64 public static byte charToByte(charc) {65 return (byte) "0123456789ABCDEF".indexOf(c);66 }67

68 /**

69 * 3、文件转byte70 *71 *@paramfilePath 文件路径72 *@returnbyte73 */

74 public static byte[] file2byte(String filePath) {75 File tradeFile = newFile(filePath);76 byte[] buffer = null;77 try{78 FileInputStream fis = newFileInputStream(tradeFile);79 ByteArrayOutputStream bos = newByteArrayOutputStream();80 byte[] b = new byte[1024];81 intn;82 while ((n = fis.read(b)) != -1) {83 bos.write(b, 0, n);84 }85 fis.close();86 bos.close();87 buffer =bos.toByteArray();88 } catch(IOException e) {89 e.printStackTrace();90 }91 returnbuffer;92 }93

94 /**

95 * 4、int转byte96 *97 *@parami int数据98 *@returnbyte99 */

100 public static byte[] intToByteArray(inti) {101 byte[] result = new byte[4];102 result[0] = (byte) ((i >> 24) & 0xFF);103 result[1] = (byte) ((i >> 16) & 0xFF);104 result[2] = (byte) ((i >> 8) & 0xFF);105 result[3] = (byte) (i & 0xFF);106 returnresult;107 }108

109 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值