【问题标题】:Conversion of array string to array ulong in c#c#中数组字符串到数组ulong的转换
【发布时间】:2018-09-26 14:21:25
【问题描述】:

我有一个包含值的字符串数组

string[] words = {"0B", "00", " 00",  "00",  "00", "07",  "3F",  "14", "1D"}; 

我需要将它转换成 ulong 数组

ulong[] words1;  

我应该如何在c#中做到这一点
我想我应该添加一些背景。
字符串中的数据来自文本框,我需要在 hexUpDown.Value 参数中写入这个文本框的内容。

【问题讨论】:

  • 你试过什么?只需谷歌搜索“将字符串转换为 ulong”,然后对数组中的每个元素重复此操作。
  • ulong words1 = Convert.ToUInt64(words[1]);已经试过了,但是当我执行它时,我收到一条错误消息“输入字符串格式不正确”
  • 并尝试尽快学习 LINQ,它会让这样的事情变得容易得多。
  • @SoptikHa 这是一个非常糟糕的建议,让程序员过度使用 LINQ 作为“让一切变得更简单的神奇工具”,而这通常会导致代码更难阅读。特别是如果您不了解背后的基础知识,这是一种很好的老式循环。
  • NumberStyles.AllowHexSpecifier 是你的朋友。

标签: c# explicit-conversion


【解决方案1】:
var ulongs = words.Select(x => ulong.Parse(x, NumberStyles.HexNumber)).ToArray();

【讨论】:

    【解决方案2】:

    如果您需要将字节组合成 64 位值,请尝试此操作(假设正确的 endieness)。

    string[] words = { "0B", "00", " 00", "00", "00", "07", "3F", "14", "1D" };
    var words64 = new List<string>();
    int wc = 0;
    var s = string.Empty;
    var results = new List<ulong>();
    
    // Concat string to make 64 bit words
    foreach (var word in words) 
    {
        // remove extra whitespace
        s += word.Trim();
        wc++;
    
        // Added the word when it's 64 bits
        if (wc % 4 == 0)
        {
            words64.Add(s);
            wc = 0;
            s = string.Empty;
        }
    }
    
    // If there are any leftover bits, append those
    if (!string.IsNullOrEmpty(s))
    {
        words64.Add(s);
    }
    
    // Now attempt to convert each string to a ulong
    foreach (var word in words64)
    {
        ulong r;
        if (ulong.TryParse(word, 
            System.Globalization.NumberStyles.AllowHexSpecifier, 
            System.Globalization.CultureInfo.InvariantCulture, 
            out r))
        {
            results.Add(r);
        }
    }
    

    结果:

    List<ulong>(3) { 184549376, 474900, 29 }
    

    【讨论】:

    • 或者,我可能更喜欢for (int i=0; i &lt; (items.Count / 4) + 1; i++) { words64.Add(string.Join(string.Empty, items.Skip(i*4).Take(4))); }
    • ulong words1 = Convert.ToUInt64(words[1],16);这对我来说比任何其他解决方案都简单,无论如何谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2015-05-22
    • 2017-10-27
    • 2015-02-21
    相关资源
    最近更新 更多