2

in c# how to convert an varto a char array. char[8] array I can guarantee this var is not too big.

such as, I have

var a = 634711440648369988;

and I want char[8] c store it.

How to do this conversion correctly? Thanks.

2
  • I changed my question from "int" to "var". Just let you know. Sorry for inconvenient Commented Apr 28, 2012 at 0:22
  • 2
    Are you trying to store the 8 bytes that make up a long in a "char" array? A c# char isn't the same as a c char. Commented Apr 28, 2012 at 0:24

5 Answers 5

2

Use BitConverter.GetBytes(long) or BitConverter.GetBytes(ulong)

Sign up to request clarification or add additional context in comments.

2 Comments

how to make sure my result array has size of 8? This is very important for me
@Anders: It depends on which overload you choose. Int64 or UInt64 inputs will produce 8 bytes out. Int32 or UInt32 inputs produce 4 bytes out. And so on. So use ulong a = 634711440648369988; instead of var, to guarantee the exact size.
1

You can just cast it to a string and use the ToCharArray method.

char [ ] c = a.ToString().ToCharArray();

3 Comments

Calling toString isn't a cast, though. It's a method call.
how to make sure my result array has size of 8? This is very important for me
@AndersLind if you call a.ToString().ToCharArray(), then the array can be pretty any length between 1 to the maximimum number of decimal digits in your number.
1

In C# there is no such thing as char[8]. An array of char would be char[].

I guess you are coming at this from a C++ viewpoint and actually want an array of bytes, of length 8. In which case the type you need is byte[]. Note that you want byte[] rather than char[] since char in C# is a 16 bit data type.

You can obtain what you need by calling BitConverter.GetBytes(). When you call this function passing an 8 byte integer, the returned array will be a byte[] with length equal to 8, as stated in the documentation.

Comments

0
int a = 123412;

char[] d = a.ToString().ToCharArray();

foreach (char c in d)
{
    Console.WriteLine(c);
}

Comments

0

Thank you everyone. I seen the question for different type. Therefore, I'm writing different types. Firstly, I did split the string to string array, Secondly, I did convert the string array to var array, Thirdly, I did convert var array to char array.

        string input="q;w;e;r;t;y";
        string[] roleSplit = new string[input.Length];
        roleSplit = input.Split(';');
        var varArray = roleSplit.SelectMany(x => x.ToCharArray());
        char[] charArray = varArray.ToArray();

Comments

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.