0

How to get first 30 bytes from string?

Eg: string phone = "My name is 绳図轉丰 blah blah"; then

Function returned "My name" (30 bytes) Thanks for help.

BinaryFormatter bf = new BinaryFormatter();
byte[] bytes;
MemoryStream ms = new MemoryStream();
string orig = "喂 Hello 谢谢 Thank You";
bf.Serialize(ms, orig);
ms.Seek(0, 0);
bytes = ms.ToArray();
MessageBox.Show("Original bytes Length: " + bytes.Length.ToString());
MessageBox.Show("Original string Length: " + orig.Length.ToString());
user2989391
  • 51
  • 1
  • 9
  • 10
    Strings don't have "bytes" (they are sequences of characters), unless you convert them to a `byte[]` - e.g. [GetBytes](http://msdn.microsoft.com/en-us/library/ds4kkd55(v=vs.110).aspx) - under a *specific* encoding. (In this case, "My name" will only be close-ish to 30 bytes under UTF32.) – user2864740 Mar 10 '14 at 20:29
  • 1
    Come on, read some docs..... – L.B Mar 10 '14 at 20:30
  • 1
    Why not type your question into a search engine? – KevinDTimm Mar 10 '14 at 20:30
  • possible duplicate of [.NET String to byte Array C#](http://stackoverflow.com/questions/472906/net-string-to-byte-array-c-sharp) – Dan Bechard Mar 10 '14 at 20:31
  • I read this answer but i not get total bytes, i wanna only 30 bytes split from string sorry for my bad English – user2989391 Mar 10 '14 at 20:33
  • @user2989391 To get the first N-bytes, with LINQ: `byte[] upToFirst30Bytes = bytes.Take(30).ToArray();` (however, the BinaryFormatter use seems suspect.) – user2864740 Mar 10 '14 at 20:36

1 Answers1

5

As others said, string itself does not have byte representation which depends on encoding used. You can try this:

Encoding.UTF8.GetBytes("Your string with some interesting data").Take(30);

But you have to remember that depending on selected encoding, values returned by GetBytes method may differ.

Chris W.
  • 346
  • 4
  • 14