Converting String to Byte Array in C# - Stack Overflow
Converting String to Byte Array in C# - Stack Overflow
if ((searchResult.Properties["user"].Coun
t > 0))
{
profile.User = System.Text.Encoding.UTF8
"user"][0]);
}
Any suggestions?
nouptime asked
8,311 ● 5 ● 18 ● 34 Apr 18 '13 at 0:50
2 Turns out there was no need for all that fuss. The
username could be fetched without encoding after
all. – nouptime Mar 14 '14 at 8:10
edited
Sep 12 '18 at 12:52
using System.Text;
Shridhar answered
1,788 ● 1 ● 10 ● 13 Dec 18 '15 at 4:40
edited
May 24 '17 at 7:50
Ali answered
3,107 ● 4 ● 35 ● 50 Jun 22 '17 at 14:59
Add a comment
Add a comment
edited
Oct 31 '20 at 9:24
JustinStolle edited
3,742 ● 3 ● 32 ● 46 Aug 31 '14 at 1:09
1 This will fail for characters that fall into the surrogate
pair range.. GetBytes will have a byte array that
misses one normal char per surrogate pair off the
end. The GetString will have empty chars at the end.
The only way it would work is if microsoft's default
were UTF32, or if characters in the surrogate pair
range were not allowed. Or is there something I'm
not seeing? The proper way is to 'encode' the string
into bytes. – Gerard ONeill Feb 17 '17 at 17:31
Add a comment
ons
{
/// <summary>
/// Creates a byte array from
the string, using the
/// System.Text.Encoding.Defa
ult encoding unless another is sp
ecified.
/// </summary>
public static byte[] ToByteAr
ray(this string str, Encoding enc
oding = Encoding.Default)
{
return encoding.GetBytes(
str);
}
}
// default encoding
byte[] default = foo.ToByteArray(
);
// custom encoding
byte[] unicode = foo.ToByteArray(
Encoding.Unicode);
Add a comment
And in reverse:
knocte edited
14.7k ● 7 ● 67 ● 111 Dec 16 '20 at 14:06
Add a comment
use this
11
return bytes;
}
Keeping it simple
Noam M edited
3,057 ● 5 ● 25 ● 38 Jan 8 '18 at 5:11
As follows:
user4726577 answered
71 ● 1 ● 1 Mar 29 '15 at 14:31
Ali edited
3,107 ● 4 ● 35 ● 50 Jul 29 '17 at 5:59
| Method |
Mean | Error | StdDe
v | Gen 0 | Gen 1 | Gen 2 | Allo
cated |
|----------------------------- |-
----------:|----------:|---------
-:|-------:|------:|------:|-----
-----:|
| UsingEncodingUnicodeGetBytes |
160.042 ns | 3.2864 ns | 6.4099 n
s | 0.0780 | - | - |
edited
Oct 16 '19 at 13:15
Algemist answered
300 ● 2 ● 10 Dec 7 '18 at 14:43
mystring.Select(Convert.ToByte).T
oArray()
Lomithrani answered
1,717 ● 3 ● 16 ● 24 Apr 12 '17 at 16:25
shA.t edited
15.3k ● 5 ● 47 ● 95 Jul 30 '17 at 3:47
Add a comment
if ( ( searchResult.Properties [
"user" ].Count > 0 ) ) {
profile.User = System.Text.Encodin
"user" ] [ 0 ].ToCharArray ().Sel
ect ( character => ( byte ) chara
cter ).ToArray () );