bytebuffer put flip compact clear 方法演示

2023-10-28

工具类

如下的类为打印bytebuffer相关数据的工具类

package cn.itcast.netty.c1;

import io.netty.util.internal.StringUtil;

import java.nio.ByteBuffer;

import static io.netty.util.internal.MathUtil.isOutOfBounds;
import static io.netty.util.internal.StringUtil.NEWLINE;

public class ByteBufferUtil {
    private static final char[] BYTE2CHAR = new char[256];
    private static final char[] HEXDUMP_TABLE = new char[256 * 4];
    private static final String[] HEXPADDING = new String[16];
    private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
    private static final String[] BYTE2HEX = new String[256];
    private static final String[] BYTEPADDING = new String[16];

    static {
        final char[] DIGITS = "0123456789abcdef".toCharArray();
        for (int i = 0; i < 256; i++) {
            HEXDUMP_TABLE[i << 1] = DIGITS[i >>> 4 & 0x0F];
            HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F];
        }

        int i;

        // Generate the lookup table for hex dump paddings
        for (i = 0; i < HEXPADDING.length; i++) {
            int padding = HEXPADDING.length - i;
            StringBuilder buf = new StringBuilder(padding * 3);
            for (int j = 0; j < padding; j++) {
                buf.append("   ");
            }
            HEXPADDING[i] = buf.toString();
        }

        // Generate the lookup table for the start-offset header in each row (up to 64KiB).
        for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i++) {
            StringBuilder buf = new StringBuilder(12);
            buf.append(NEWLINE);
            buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
            buf.setCharAt(buf.length() - 9, '|');
            buf.append('|');
            HEXDUMP_ROWPREFIXES[i] = buf.toString();
        }

        // Generate the lookup table for byte-to-hex-dump conversion
        for (i = 0; i < BYTE2HEX.length; i++) {
            BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
        }

        // Generate the lookup table for byte dump paddings
        for (i = 0; i < BYTEPADDING.length; i++) {
            int padding = BYTEPADDING.length - i;
            StringBuilder buf = new StringBuilder(padding);
            for (int j = 0; j < padding; j++) {
                buf.append(' ');
            }
            BYTEPADDING[i] = buf.toString();
        }

        // Generate the lookup table for byte-to-char conversion
        for (i = 0; i < BYTE2CHAR.length; i++) {
            if (i <= 0x1f || i >= 0x7f) {
                BYTE2CHAR[i] = '.';
            } else {
                BYTE2CHAR[i] = (char) i;
            }
        }
    }

    /**
     * 打印所有内容
     * @param buffer
     */
    public static void debugAll(ByteBuffer buffer) {
        int oldlimit = buffer.limit();
        buffer.limit(buffer.capacity());
        StringBuilder origin = new StringBuilder(256);
        appendPrettyHexDump(origin, buffer, 0, buffer.capacity());
        System.out.println("+--------+-------------------- all ------------------------+----------------+");
        System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), oldlimit);
        System.out.println(origin);
        buffer.limit(oldlimit);
    }

    /**
     * 打印可读取内容
     * @param buffer
     */
    public static void debugRead(ByteBuffer buffer) {
        StringBuilder builder = new StringBuilder(256);
        appendPrettyHexDump(builder, buffer, buffer.position(), buffer.limit() - buffer.position());
        System.out.println("+--------+-------------------- read -----------------------+----------------+");
        System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), buffer.limit());
        System.out.println(builder);
    }

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put(new byte[]{97, 98, 99, 100});
        debugAll(buffer);
    }

    private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
        if (isOutOfBounds(offset, length, buf.capacity())) {
            throw new IndexOutOfBoundsException(
                    "expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length
                            + ") <= " + "buf.capacity(" + buf.capacity() + ')');
        }
        if (length == 0) {
            return;
        }
        dump.append(
                "         +-------------------------------------------------+" +
                        NEWLINE + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" +
                        NEWLINE + "+--------+-------------------------------------------------+----------------+");

        final int startIndex = offset;
        final int fullRows = length >>> 4;
        final int remainder = length & 0xF;

        // Dump the rows which have 16 bytes.
        for (int row = 0; row < fullRows; row++) {
            int rowStartIndex = (row << 4) + startIndex;

            // Per-row prefix.
            appendHexDumpRowPrefix(dump, row, rowStartIndex);

            // Hex dump
            int rowEndIndex = rowStartIndex + 16;
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
            }
            dump.append(" |");

            // ASCII dump
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
            }
            dump.append('|');
        }

        // Dump the last row which has less than 16 bytes.
        if (remainder != 0) {
            int rowStartIndex = (fullRows << 4) + startIndex;
            appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);

            // Hex dump
            int rowEndIndex = rowStartIndex + remainder;
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
            }
            dump.append(HEXPADDING[remainder]);
            dump.append(" |");

            // Ascii dump
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
            }
            dump.append(BYTEPADDING[remainder]);
            dump.append('|');
        }

        dump.append(NEWLINE +
                "+--------+-------------------------------------------------+----------------+");
    }

    private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
        if (row < HEXDUMP_ROWPREFIXES.length) {
            dump.append(HEXDUMP_ROWPREFIXES[row]);
        } else {
            dump.append(NEWLINE);
            dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
            dump.setCharAt(dump.length() - 9, '|');
            dump.append('|');
        }
    }

    public static short getUnsignedByte(ByteBuffer buffer, int index) {
        return (short) (buffer.get(index) & 0xFF);
    }
}

put 方法演示

public class TestByteBufferReadWrite {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put((byte) 0x61);
        debugAll(buffer);
    }
}

打印如下, postion 位置为1, 有一个数据为61, 10进制是a

+--------+-------------------- all ------------------------+----------------+
position: [1], limit: [10]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 00 00 00 00 00 00 00 00 00                   |a.........      |
+--------+-------------------------------------------------+----------------+

存放入数组

public class TestByteBufferReadWrite {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put((byte) 0x61);
        debugAll(buffer);
		
		buffer.put(new byte[]{0x62, 0x63, 0x64});
        debugAll(buffer);
    }
}

控制台打印如下 : 存放了四个数据, position为4

+--------+-------------------- all ------------------------+----------------+
position: [1], limit: [10]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 00 00 00 00 00 00 00 00 00                   |a.........      |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [4], limit: [10]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 00 00 00 00 00 00                   |abcd......      |
+--------+-------------------------------------------------+----------------+

flip get 方法演示

  public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put((byte) 0x61);
        debugAll(buffer);
        //
        buffer.put(new byte[]{0x62, 0x63, 0x64});
        debugAll(buffer);
         进入读模式
        buffer.flip();
        System.out.println(buffer.get());
        debugAll(buffer);
    }

调用flip后, 进入读模式, 可以看到打印了97, position 在下标为1的位置.

+--------+-------------------- all ------------------------+----------------+
position: [1], limit: [10]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 00 00 00 00 00 00 00 00 00                   |a.........      |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [4], limit: [10]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 00 00 00 00 00 00                   |abcd......      |
+--------+-------------------------------------------------+----------------+
97
+--------+-------------------- all ------------------------+----------------+
position: [1], limit: [4]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 00 00 00 00 00 00                   |abcd......      |
+--------+-------------------------------------------------+----------------+

compact 方法演示

compact 方法用于未读取完数据时, 写入数据, 例如上一步, 里面有四个数据, 只读取了一个数据61, 调用compact 方法进入 写模式, 可以保证, 未读取完的数据, 不会丢失.

 public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put((byte) 0x61);
        debugAll(buffer);
        //
        buffer.put(new byte[]{0x62, 0x63, 0x64});
        debugAll(buffer);
        //
         进入读模式
        buffer.flip();
        System.out.println(buffer.get());
        debugAll(buffer);

        buffer.compact();
        debugAll(buffer);
        buffer.put(new byte[]{0x65, 0x66});
        debugAll(buffer);
    }

控制台打印如下, 只截取了最后两次的打印, 可以看到是从position3的位置开始写入, 保留了之前没有读取的数据(62, 63, 64)

+--------+-------------------- all ------------------------+----------------+
position: [3], limit: [10]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 63 64 64 00 00 00 00 00 00                   |bcdd......      |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [5], limit: [10]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 63 64 65 66 00 00 00 00 00                   |bcdef.....      |
+--------+-------------------------------------------------+----------------+

如果改成clear写入

       buffer.clear();
        debugAll(buffer);
        buffer.put(new byte[]{0x65, 0x66});
        debugAll(buffer);

控制台打印如下, 可以看到position 从0开始了, 把65, 66 写入到了0 和1的位置, 把原有的61,62覆盖了.

+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [10]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 00 00 00 00 00 00                   |abcd......      |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [2], limit: [10]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 65 66 63 64 00 00 00 00 00 00                   |efcd......      |
+--------+-------------------------------------------------+----------------+

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

bytebuffer put flip compact clear 方法演示 的相关文章

随机推荐

  • 【Python开发】Flask开发实战:个人博客(四)

    Flask开发实战 个人博客 四 本篇博客将是 Flask开发实战 个人博客 的最后一篇 本篇文章将会详细介绍博客后台的编写 为了支持管理员管理文章 分类 评论和链接 我们需要提供后台管理功能 通常来说 程序的这一部分被称为管理后台 控制面
  • 程序运行时的存储结构

    程序运行时的存储结构 目标程序在目标机器环境下运行时 只是在自己的运行时的存储空间内完成执行 通常 在有操作系统的情况下 程序在自己的逻辑存储空间内存储和运行 因此 编译程序在生成目标代码时应该明确程序的所有对象在逻辑存储空间是如何存储的
  • 安装完Ubuntu 17.10后要做的几件事

    前几天Ubuntu 17 10终于出来了 正好前几天我电脑重装系统 顺便留了一个分区用来装Linux 所以就在我电脑上安装了Ubuntu 17 10 安装过程就不说了 图形化安装程序 基本安装过几次就熟悉了 所以重点 还是安装完成之后的美化
  • 【Golang 面试算法二叉树 手动建树】

    Golang 面试算法二叉树 手动建树 前言 代码实现 前言 面试中有很多有关二叉树的题目 且需要手动建树 这里记录一下如何用Golang来快速构建一个二叉树 代码实现 我们知道二叉树可以扁平化到数组中 当前节点的左右子节点的在数组中的下标
  • Allegro输出光绘文件规范

    光绘输出操作规范 1 1添加钻孔表 添加钻孔表的具体步骤为 1 通过屏幕右边的Visibility选项的Views列表 将Drill层打开 2 将Visibility选项中的PIN和Via选项都选中 见下图所示 1 2添加钻孔文件 参数设好
  • pyTorch onnx 学习(二)

    添加自定义的onnx operations 在pyTorch中定义的网络图以及其运算 在onnx中不一定支持 因此 需要自定义的添加operators 如果onnx支持则可以直接使用 一下是支持的网络以及运算 add nonzero alp
  • Android定制实现上网限制iptables

    随着智能手机和平板的普及 现在的孩子几乎人手一部手机或平板 所以常常能看到一些孩子抱着手机玩游戏或是浏览网页 一玩就是一整天 家长们不免担心自己的孩子是不是会浏览不适合他们看的网页 是不是玩的时间太长 导致他们对其他的事情 比如运动 学习和
  • Windows pytesseract image_to_osd Invalid resolution 0 dpi. Using 70 instead. Too few characters报错及解决

    Windows pytesseract image to osd Invalid resolution 0 dpi Using 70 instead Too few characters报错及解决 1 安装 python3 7 pip in
  • otsu算法_Otsu 灰度图像阈值算法及实现

    人工智能导论课的第一次作业 文末提供 HTML 文件源码 可直接体验 一 简介 我们要做的 其实就是将一张 彩色 图片 转成黑白图片 二值图 二值图 只有黑色或白色 000 或 fff 0 或 255 看看效果图就基本了解了 左原图 右图经
  • Shell Script—多行注释

    在Shell脚本中 没有专门的多行注释 但可以使用一些技巧来实现多行注释的效果 以下是几种实现多行注释的方式 1 使用 使用多个 字符号 在每一行的最前面添加 字符 即可实现注释 bin sh 这是一段示例代码 此处使用了多行注释 注释语法
  • HIVE厂牌艺人_说唱厂牌 Vol.2:洛杉矶天才厂牌Odd Future Records的开始到结束

    We re F kin Radical been F kin Awesome我们太TMD激进 太TMD耀眼Talked a lotta sh t so far words you re at a loss说着一大堆胡话 让你们都不知所措了
  • resnet18实现cifar10分类

    实验步骤 搭建resnet18网络 数据集加载 模型训练和改进 分析评估 Kaggle提交 网络构建 实验初期拟采用torchvision中实现的resnet18作为网络结构 为了方便修改网络结构 于是重新实现了resnet18网络 res
  • 大数据电影可视化系统

    作者简介 大数据专业硕士在读 CSDN人工智能领域博客专家 阿里云专家博主 专注大数据与人工智能知识分享 专栏推荐 目前在写一个CV方向专栏 后期会更新不限于目标检测 OCR 图像分类 图像分割等方向 虽然付费但会长期更新且价格便宜 感兴趣
  • Conda、Git、pip设置代理教程 解决Torch not compiled with CUDA enabled问题 pip缓存坑 No module named “Crypto“

    Conda设置代理 总结 pip config set global proxy http 127 0 0 1 7890 git config global http proxy http 127 0 0 1 7890 git config
  • mysql密码错误_mysql密码正确却提示错误, 不输入密码反而能登录

    今天部署阿里云服务器 发现之前可以连接的mysql服务器突然连接不上了 密码我确认是正确的 但登录时就是显示密码错误 很崩溃 差点气得我就想重装mysql了 好在经过几番苦寻找到了以下能解决我问题的资料 成功解决了我的问题 万分感谢 便借鉴
  • 15.2 CVPR 会议的时间

    http www cvpapers com cvpr2014 html 表里的P代表paper deadline http iris usc edu Information Iris Conferences html 下面这张表早晚得过期
  • 决策树——分类——鸢尾花(调用api)

    import numpy as np from sklearn tree import DecisionTreeClassifier from sklearn import datasets from sklearn import cros
  • element-ui el-table sortable属性 参数详解

    表格组件的排序功能 点击排序表头可以进行升序和降序进行排序 上代码
  • TCP/IP Illustrated Episode 15

    Duplex Mismatch Historically there have been some interoperability problems using autonegotiation especially when a comp
  • bytebuffer put flip compact clear 方法演示

    文章目录 工具类 put 方法演示 flip get 方法演示 compact 方法演示 工具类 如下的类为打印bytebuffer相关数据的工具类 package cn itcast netty c1 import io netty ut