none
function System.Text.Encoding.ASCII.GetString(bytes) return null. RRS feed

  • Question

  • I like to store byte array as string , like following code  .

    Dim bytes(80) As Byte
    bytes(50) = 1
    Dim str As String = System.Text.Encoding.ASCII.GetString(bytes)

    However, str = "". why?
    Wednesday, February 20, 2013 3:13 AM

Answers

  • Change to bytes(50) = 65 and try it.
    Wednesday, February 20, 2013 3:35 AM
  • In addition to John's demonstration that your string is not empty, I suggest that if what you are wanting to do is to write a Byte array to a file, you don't need to try to convert it to a string in any case. You can use System.IO.BinaryWriter to write the array of Byte directly to a file (use the Write(Byte()) method).

    I don't understand your comment about saving space. Writing the array of Byte directly to file will require one byte on file for each Byte in the array. That's as little space as you can use without attempting to compress the data.


    Thursday, February 21, 2013 2:23 AM

All replies

  • Change to bytes(50) = 65 and try it.
    Wednesday, February 20, 2013 3:35 AM
  • Could you tell the reason?
    Wednesday, February 20, 2013 5:43 AM
  • The reason for what?  What are you trying to do? 
    Wednesday, February 20, 2013 6:29 AM
  • why str = ""?
    I like to store byte array in a file. the array is very large. so i store the array as unicode/ASCII to save space.  However, sometimes the str is null.  
    Thursday, February 21, 2013 12:40 AM
  • why str = ""?
    I like to store byte array in a file. the array is very large. so i store the array as unicode/ASCII to save space.  However, sometimes the str is null.  

    What str is "".  A string of length 81 is not equal to string.empty,  nor is it equal to nothing.  Byte arrays and strings aren't interchangable.

    Try this code:

        Dim bytes(80) As Byte
        bytes(50) = 1
        
    Dim str As String = System.Text.Encoding.ASCII.GetString(bytes)
        
    MessageBox.Show("The length of str is " + str.Length.ToString)



    • Edited by JohnWein Thursday, February 21, 2013 1:21 AM
    Thursday, February 21, 2013 1:12 AM
  • In addition to John's demonstration that your string is not empty, I suggest that if what you are wanting to do is to write a Byte array to a file, you don't need to try to convert it to a string in any case. You can use System.IO.BinaryWriter to write the array of Byte directly to a file (use the Write(Byte()) method).

    I don't understand your comment about saving space. Writing the array of Byte directly to file will require one byte on file for each Byte in the array. That's as little space as you can use without attempting to compress the data.


    Thursday, February 21, 2013 2:23 AM