简体   繁体   中英

Conversion of array string to array ulong in c#

I have a array of strings having values

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

I need it to convert into array of ulong

ulong[] words1;  

How should I do it in c#
I think I should add some background.
The data in the string is coming from textbox and I need to write the content of this textbox in the hexUpDown.Value parameter.

var ulongs = words.Select(x => ulong.Parse(x, NumberStyles.HexNumber)).ToArray();

If you need to combine the bytes into 64 bit values then try this (assumes correct 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);
    }
}

Results:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM