MINA源码分析---学习mina中整数和网络字节的转换处理

本文深入分析MINA框架中如何处理网络字节与计算机整数之间的转换,包括大端小端字节序的转换操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


主要学习网络字节和计算机上表示的整数之间相互转换以及和小端字节序的转换


package org.apache.mina.proxy.utils;

import java.io.UnsupportedEncodingException;

/**
 * ByteUtilities.java - Byte manipulation functions.

 * @since MINA 2.0.0-M3
 */
public class ByteUtilities {

    /**
     * Returns the integer represented by up to 4 bytes in network byte order.
     * 把网络字节序的4字节转换成整数
     * @param buf the buffer to read the bytes from
     * @param start
     * @param count
     * @return
     */
    public static int networkByteOrderToInt(byte[] buf, int start, int count) {
        if (count > 4) {
            throw new IllegalArgumentException(
                    "Cannot handle more than 4 bytes");
        }

        int result = 0;
        //(这里面是考虑32位机器)采用与低8位字节做或操作,然后左移8位,把4个字节变成一个整数的32位
        for (int i = 0; i < count; i++) {
            result <<= 8;
            result |= (buf[start + i] & 0xff);
        }

        return result;
    }

    /**
     * Encodes an integer into up to 4 bytes in network byte order.
     * 把一个整数编码成4个网络字节序的字节
     * @param num the int to convert to a byte array
     * @param count the number of reserved bytes for the write operation
     * @return the resulting byte array
     */
    public static byte[] intToNetworkByteOrder(int num, int count) {
        byte[] buf = new byte[count];
        intToNetworkByteOrder(num, buf, 0, count);
        
        return buf;
    }
    
    /**
     * Encodes an integer into up to 4 bytes in network byte order in the 
     * supplied buffer starting at <code>start</code> offset and writing
     * <code>count</code> bytes.
     * 
     * @param num the int to convert to a byte array
     * @param buf the buffer to write the bytes to
     * @param start the offset from beginning for the write operation
     * @param count the number of reserved bytes for the write operation
     */
    public static void intToNetworkByteOrder(int num, byte[] buf, int start,
            int count) {
        if
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值