首页 > 其他分享 >byte[]、list<byte>数组类型的几个自定义扩展方法

byte[]、list<byte>数组类型的几个自定义扩展方法

时间:2023-11-07 15:00:26浏览次数:27  
标签:return string 自定义 list Length ToString byte

byte[]、list<byte>数组类型的几个自定义扩展方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace iPublic.类型扩展方法
{
    /// <summary>
    /// 类型的扩展方法,用起来方便的
    /// 修改记录:
    ///   20230415,海宏软件,zch,List的
    /// </summary>
    public static class ExtendMethods
    {


        /// <summary>
        /// 十六进制字符串转成byte数组,用空格、减号分割
        /// </summary>
        /// <param name="InString"></param>
        /// <returns></returns>
        public static byte[] HexStringToByte(this string InString)
        {
            string[] ByteStrings;
            ByteStrings = InString.Split(' ', '-');
            byte[] ByteOut;
            ByteOut = new byte[ByteStrings.Length];
            for (int i = 0; i <= ByteStrings.Length - 1; i++)
            {
                ByteOut[i] = Byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);
            }
            return ByteOut;
        }


        #region //扩展List<int>的ToString方法
        /// <summary>
        /// 扩展List<int>的ToString方法,注意,如果参数和基类一样,会调用基类的,这里就不执行了
        /// </summary>
        /// <param name="list"></param>
        /// <param name="连接符"></param>
        /// <returns></returns>
        public static string ToString(this List<byte> list, string 连接符)
        {
            if (list == null || list.Count < 1) return "";
            string s = "", sChar = 连接符, s2 = "";
            if (string.IsNullOrEmpty(sChar)) sChar = " ";
            //传统转换法,速度太慢,5M大概需要2分钟多
            //foreach (byte itm in list) s += sChar + itm.ToString("X2");
            //系统自带转换法,5M大概需要2秒
            s = BitConverter.ToString(list.ToArray());
            if (!string.IsNullOrEmpty(sChar)) s = s.Replace("-", sChar);
            
            //完成
            return s;
        }
        #endregion


        #region //扩展byte[]的ToString
        /// <summary>
        /// 扩展byte[]的ToString方法,注意,如果参数和基类一样,会调用基类的,这里就不执行了
        /// </summary>
        /// <param name="list"></param>
        /// <param name="连接符"></param>
        /// <returns></returns>
        public static string ToString(this byte[] list, string 连接符)
        {
            if (list == null || list.Length < 1) return "";
            string s = "", s2 = "", sChar = 连接符;
            //传统转换法速度太慢,5M大概需要2分钟多
            //foreach (byte itm in list) s += (s == "" ? "" : 连接符) + itm.ToString("X2");
            //系统自带转换法,5M大概需要2秒
            s = BitConverter.ToString(list);
            if (!string.IsNullOrEmpty(sChar)) s = s.Replace("-", sChar);
            //完成
            return s;
        }
        #endregion


        #region //IndexOfByte数组
        /// <summary>  
        /// 报告指定的 System.Byte[] 在此实例中的第一个匹配项的索引。
        /// 参考:https://www.iteye.com/blog/testcs-dn-2099443
        /// </summary>  
        /// <param name="srcBytes">被执行查找的 System.Byte[]。</param>  
        /// <param name="searchBytes">要查找的 System.Byte[]。</param>  
        /// <returns>如果找到该字节数组,则为 searchBytes 的索引位置;如果未找到该字节数组,则为 -1。如果 searchBytes 为 null 或者长度为0,则返回值为 -1。</returns>  
        public static int IndexOf(this byte[] srcBytes, byte[] searchBytes)
        {
            return IndexOf(srcBytes, searchBytes, 0);
        }
        public static int IndexOf(this byte[] srcBytes, byte[] searchBytes, int 开始位置)
        {
            if (srcBytes == null) { return -1; }
            if (searchBytes == null) { return -1; }
            if (srcBytes.Length == 0) { return -1; }
            if (searchBytes.Length == 0) { return -1; }
            if (srcBytes.Length < searchBytes.Length) { return -1; }
            int nSrc = srcBytes.Length, nSearch = searchBytes.Length;
            for (int i = 开始位置; i < nSrc /*- searchBytes.Length*/; i++)
            {
                if (srcBytes[i] != searchBytes[0]) continue;
                if (nSearch == 1) { return i; }
                if (i + nSearch > nSrc) return -1;  //查找

                bool flag = true;
                for (int j = 1; j < nSearch; j++)
                {
                    if (srcBytes[i + j] != searchBytes[j])
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    return i;
                }
            }
            return -1;
        }
        #endregion


        #region //byte[].split拆分成多个数组
        public static List<byte[]> split(this byte[] src, List<byte[]> separator)
        {
            List<byte[]> result = new List<byte[]>();
            byte[] buf = null, bufAll = src;
            //Dictionary<int, int> indexs = new Dictionary<int, int>();
            int nIdx = 0, nLastIdx = 0, nLen = src.Length;
            while (nLastIdx < src.Length)
            {
                byte[] finder = null;
                foreach (var itm in separator)
                {
                    nIdx = src.IndexOf(itm, nLastIdx);  //查找
                    if (nIdx >= 0) { finder = itm; break; } //找到了,记下来
                }
                if (finder != null)
                {
                    if (nIdx <= nLastIdx) result.Add(null);  //第一位就是
                    else
                    {   //取出有效数据,放入结果中
                        buf = src.Skip(nLastIdx).Take(nIdx - nLastIdx).ToArray();
                        result.Add(buf);
                    }
                    nLastIdx = nIdx + finder.Length;    //上次的位置
                }
                else
                {   //全部
                    if (src.Length > nLastIdx)
                    {
                        buf = src.Skip(nLastIdx).Take(src.Length - nLastIdx).ToArray();
                        result.Add(buf);
                    }
                    nLastIdx = src.Length;
                }
            }
            //
            return result;
        }
        #endregion


    }



}

  

想不到BitConvert.ToString的速度会差这么多。用法:

using namespace iPublic.类型扩展方法;

byte[] buf=new byte[];

.........

string s=buf.ToString("");

 

标签:return,string,自定义,list,Length,ToString,byte
From: https://www.cnblogs.com/HaiHong/p/17815028.html

相关文章

  • 一个List对象,想把特定的值排在最前面进行处理
    今天遇到一个需求,要把list中的某些特定的值排在最前面处理,所以就要对list进行排序,搜索了一下进行总结首先对List<String>根据特定的值进行排序List<String>list=Arrays.asList("apple","banana","cherry","date","sss","fig");Li......
  • springboot nacos使用yaml配置list方式
    方式一配置项:app:demo:list1:xiaohong,xiaominglist2:>xiaohong,xiaominglist1和list2看起来是2种风格,其实都是同一种写法,以逗号分隔java代码:@Data@ComponentpublicclassAppConfig1{@Value("${app.demo.list1}")privateList<Strin......
  • bitsdojo_window自定义导航以及关闭按钮
    1、Windows里面的配置在应用程序文件夹中,转到windows\runner\main.cpp,并在文件开头添加以下两行:#include<bitsdojo_window_windows/bitsdojo_window_plugin.h>autobdw=bitsdojo_window_configure(BDW_CUSTOM_FRAME|BDW_HIDE_ON_STARTUP);2、macOS里面的配置1、在应用程......
  • 界面组件Telerik UI for WinForms中文教程 - 如何自定义应用程序文件窗口?
    TelerikUIforWinForms包含了一个高度可定制的组件,它取代了.NET中默认的OpenFileDialog。在下一个更新版本中,会发布一个向对话框浏览器提那家自定义位置的请求功能,本文演示了这个和另一个自定义功能,它可以帮助用户在浏览文件夹时快速选择最后修改的文件,自定义将根据最近的日期/......
  • js 数组按指定字段转map-list结构
    js数组按指定字段转map-list结构背景介绍在开发过程中经常会出现接口返回整个数组,我们需要将数组进行二次处理,如下格式按照不同功能模块(type)进行数据拆分原始数据constlist=[{"type":"red","id":1,"name":"a","count":1}, {"type":"red","......
  • .NET(C#) LinkedList、Queue<T>和Stack<T>的使用
    本文主要介绍.NET(C#)中,LinkedList链表、Queue<T>队列和Stack<T>堆栈的使用,以及相关的示例代码。1、LinkedList(链表)链表中元素存储内存中是不连续分配,每个元素都有记录前后节点,节点值可以重复,不能通过下标访问,泛型的使用保证类型安全,可以避免装箱拆箱,找元素就只能遍历,查找不方......
  • C#学习之ListBox,ComboBox,CheckListBox
    ListBox(文本列表)常用属性:Items:描述:ListBox中的项列表。默认值:空用法:可以使用Add(),AddRange(),Insert(),Remove(),Clear(),等方法来对Items集合进行管理。SelectedIndex:描述:ListBox中当前选择项的索引。默认值:-1(表示没有选中项)用法:通过设置或读取该属......
  • Linux Vim批量注释和自定义注释
    使用Vim编辑Shell脚本,在进行调试时,需要进行多行的注释,每次都要先切换到输入模式,在行首输入注释符"#"再退回命令模式,非常麻烦。连续行的注释其实可以用替换命令来完成。换句话说,在指定范围行加"#"注释,可以使用":起始行,终止行s/^/#/g",例如::1,10s/^/#/g表示在第1~10行行首加"#......
  • 通过mybatis-plus的自定义拦截器实现控制 mybatis-plus的全局逻辑删除字段的控制 (修改
    需求:过滤部分请求不实现mybatis-plus的逻辑删除看到网上关于mybatis-plus的自定义拦截器的文章有的少想了想自己写了一篇欢迎参考指正通过springboot的拦截器在请求进来时标记需要实现的需求的逻辑importlombok.Data;@DatapublicclassSyncBo{privateBoolean......
  • jupyter 下 bitandbytes报错记录
    背景:在jupyter中加载baichuan大模型时报错报错一:frompeftimportPeftModel 报错报错提示:python-mbitsandbytes执行python-mbitsandbytes时又报错,报错内容为:Traceback(mostrecentcalllast):File"/home/miniconda3/envs/vllm/lib/python3.10/runpy.py",lin......