-4

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.

7
  • What have you tried? Just google for "convert string to ulong" and then repeat that for every element in your array. Commented Sep 26, 2018 at 14:22
  • ulong words1 = Convert.ToUInt64(words[1]); Have tried it, but when I execute it I get a error saying "Input string not in correct format" Commented Sep 26, 2018 at 14:25
  • And try to learn LINQ as soon as possible, it'll make things like this much easier. Commented Sep 26, 2018 at 14:25
  • @SoptikHa That´s a really bad suggestion and makes programmers over-use LINQ as "magic tool to make everything easier", while that often leads to harder to read code. In particular if you don´t know the basics behind, which is good old-style looping. Commented Sep 26, 2018 at 14:27
  • 1
    NumberStyles.AllowHexSpecifier is your friend. Commented Sep 26, 2018 at 14:28

2 Answers 2

2
var ulongs = words.Select(x => ulong.Parse(x, NumberStyles.HexNumber)).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

-1

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 }

2 Comments

Alternatively, I might prefer for (int i=0; i < (items.Count / 4) + 1; i++) { words64.Add(string.Join(string.Empty, items.Skip(i*4).Take(4))); }
ulong words1 = Convert.ToUInt64(words[1],16); This Simply worked for me than any other solutions, bur thanks anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.