• int 转换 byte[] 或 byte[] 转换 int


    byte[] bs = BitConverter.GetBytes(0x1234);
    Console.WriteLine(bs[0].ToString("X2") + " " + bs[1].ToString("X2"));
    // output: 34 12  低位在前,高位在后
    
    
    byte[] bs2 = BitConverter.GetBytes(System.Net.IPAddress.HostToNetworkOrder((short)0x1234));
    Console.WriteLine(bs2[0].ToString("X2") + " " + bs2[1].ToString("X2"));
    // output: 12 34 高位在前,低位在后
    
    byte[] bs3 = BitConverter.GetBytes(0x1234);
    Array.Reverse(bs3);
    Console.WriteLine(bs3[0].ToString("X2") + " " + bs3[1].ToString("X2"));
    // output: 12 34 高位在前,低位在后

    一、int 转换 byte[]

    低位在前,高位在后

    public
    static byte[] ConvertInt2Byte(int tmp) { byte[] result = BitConverter.GetBytes(tmp); return result; }
    高位在前,低位在后

    public
    static byte[] ConvertInt2Byte(int tmp) { byte[] result = BitConverter.GetBytes(tmp); //反转数组 Array.Reverse(result); return result; }

    二、byte[] 转换 int

    1、转换例子

    byte[] bytes = { 0, 0, 0, 25 };
    
    // If the system architecture is little-endian (that is, little end first),
    // reverse the byte array.
    if (BitConverter.IsLittleEndian)
        Array.Reverse(bytes);
    
    int i = BitConverter.ToInt32(bytes, 0);
    Console.WriteLine("int: {0}", i);
    // Output: int: 25

    2、函数解释

    public static int ToInt32(
        byte[] value,
        int startIndex
    )

    功能:
    返回由字节数组中指定位置的四个字节转换来的 32 位有符号整数。

    参数

    value
    类型:System.Byte[]
    字节数组。
    
    
    startIndex
    类型:System.Int32
    value 内的起始位置。
     
  • 相关阅读:
    Xpath语法
    Centos 6.5 本地局域网基于HTTP搭建YUM
    前端接口自动化测试工具-DOClever使用介绍(转载)
    mysql指令
    vue+element+echarts饼状图+可折叠列表
    vue+element+echarts柱状图+列表
    缓冲流
    查询同一张表符合条件的某些数据的id拼接成一个字段返回
    Properties集合
    JDK7&JDK9处理异常新特性
  • 原文地址:https://www.cnblogs.com/craigtao/p/4103220.html
Copyright © 2020-2023  润新知