byte[]字节操作:byte[] 截取长度&byte[]数组转16进制&byte[]转数据类型工具类

您所在的位置:网站首页 byte转成16进制 byte[]字节操作:byte[] 截取长度&byte[]数组转16进制&byte[]转数据类型工具类

byte[]字节操作:byte[] 截取长度&byte[]数组转16进制&byte[]转数据类型工具类

2023-07-18 13:36| 来源: 网络整理| 查看: 265

一.字节定义

字节(Byte)是计算机信息技术用于计量存储容量的一种计量单位,也表示一些计算机编程语言中的数据类型和语言字符。Byte是从0-255的无符号类型,所以不能表示负数。

Byte即字节的意思,通常在读取非文本文件时(如图片,声音,可执行文件)需要用字节数组来保存文件的内容。在下载文件时,也是用byte数组作临时的缓冲器接收文件内容。所以说byte在文件操作时是必不可少的。不管是对文件写入还是读取都要用到。

先来了解一下数组的定义:

byte [] aa = {0,1,2,3,4,5}; //字节数组赋值 byte[] by = new byte[10]; //字节数组定义空间 二、实际操作字节截取长度方式

前段时间因为项目的需求定义需要从字节流的字节数据中取出来某一个位置到某一个位置的字节数据。

/** * @description: 截取数据长度 * @param src begin(起始位置) count(长度) * @return byte[] * @author panlupeng * @date 2021/12/1 10:40 */ public static byte[] subBytes(byte[]src,int begin,int count){ byte[]bs=new byte[count]; for(int i=begin;i byte [] aa = {0,1,2,3,4,5}; byte[] bytes = subBytes(aa, 0, 3); for (byte aByte : bytes) { System.out.println(aByte); } } 三.数组转16进制

现目前方法是倒叙的 是吧数组里边的数字进行倒叙转化了,用到的小伙伴请把 int n = bytes.length-1 换成int n=0 然后i++ 就OK;

/** * @description: 数组转16进制 * @param bytes * @return String * @date 2021/12/1 10:43 */ public static String byteToHex(byte[] bytes){ String strHex = ""; StringBuilder sb = new StringBuilder(""); for (int n = bytes.length-1; n >=0; n--) { strHex = Integer.toHexString(bytes[n] & 0xFF); sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示,位数不够,高位补0 } return sb.toString().trim(); }

在这里插入图片描述

四、数组转类型大全 /** * @description: byte[]转double * @param b * @date 2021/12/8 11:01 */ public static double getDouble(byte[] b) { long m; m = b[0]; m &= 0xff; m |= ((long) b[1] String keyword = null; try { keyword = new String(str,"GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return keyword; } /** * @description: byte[]转Int * @param b * @date 2021/12/8 11:01 */ public static int byteToInt(byte[] b) { int s = 0; int s0 = b[0] & 0xff;// 最低位 int s1 = b[1] & 0xff; int s2 = b[2] & 0xff; int s3 = b[3] & 0xff; s3 accum |= (b[shiftBy] & 0xff) throw new NumberFormatException("null"); } if (radix throw new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX"); } long result = 0; boolean negative = false; int i = 0, len = s.length(); long limit = -Long.MAX_VALUE; long multmin; int digit; if (len > 0) { char firstChar = s.charAt(0); if (firstChar negative = true; limit = Long.MIN_VALUE; } else if (firstChar != '+') throw NumberFormatException.forInputString(s); if (len == 1) // Cannot have lone "+" or "-" throw NumberFormatException.forInputString(s); i++; } multmin = limit / radix; while (i throw NumberFormatException.forInputString(s); } if (result throw NumberFormatException.forInputString(s); } result -= digit; } } else { throw NumberFormatException.forInputString(s); } return negative ? result : -result; }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3