Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert charArray to byteArray

Tags:

c#

linq

I have a string which under all circumstances satisfies ([a-zA-Z0-9])*, and I want to let it run through sha1.

So how do I convert the string (or the char array obtained using ToCharArray()) to a byte array?

All answers I found so far have a big bunch of comments why the conversion from string to byte array is evil, they provide links to character encoding tutorials, and include a bunch of character encodings bloating the code.

Under my circumstances, conversion should be a LINQ oneliner, safe and neat.

I tried:

sha.ComputeHash(validator.ToCharArray().ToArray<byte>())

and I played around as far as my LINQ knowledge goes:

sha.ComputeHash(validator.ToCharArray().ToArray<byte>(c => (byte)c))
like image 956
Alexander Avatar asked Mar 21 '14 14:03

Alexander


People also ask

How do you turn an object into a ByteArray?

Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

How do you convert int to ByteArray?

The Ints class also has a toByteArray() method that can be used to convert an int value to a byte array: byte[] bytes = Ints. toByteArray(value);

How do I turn a char array into a string?

char[] arr = { 'p', 'q', 'r', 's' }; The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);


2 Answers

validator.Select(c => (byte)c).ToArray()

Will also work. The "string" type supports "IEnumerable", so you can use LINQ directly with one.

The "Select" method allows you specify a lambda to customize your output. This replaces what you were trying to do with the "ToArray(c => (byte)c))".

like image 171
Yves Dubois Avatar answered Sep 22 '22 07:09

Yves Dubois


Encoding.GetEncoding("UTF-8").GetBytes(chararray);
like image 42
Konstantin Avatar answered Sep 24 '22 07:09

Konstantin