zoukankan      html  css  js  c++  java
  • 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 内的起始位置。
     
  • 相关阅读:
    PAT A1017 Queueing at Bank [硬核模拟]
    PAT A1105 Spiral Matrix [硬核模拟]
    PAT A1153 Decode Registration Card of PAT [排序模拟]
    PAT A1139 First Contact [图]
    jquery的animate动画
    wordpress建站过程5——footer.php
    wordpress建站过程4——index.php
    wordpress建站过程3——header.php
    HTML中加载flash方法
    轮播图的原理
  • 原文地址:https://www.cnblogs.com/craigtao/p/4103220.html
Copyright © 2011-2022 走看看