none
Remove null Bytes from a Byte() RRS feed

  • Question

  • Hey guys,

    I have a function that returns a byte(), the only problem is that the array most times is to long and has 4 or 5 excess null bytes. I want to remove them and tried everything, but I cant seem to find anything that works. Do you guys maybe know a solution to my problem? Thanks in advance.

    Feanaro

    Monday, June 27, 2011 8:05 PM

Answers

  • So you want to trim the end of the byte array of 0s?

    Something like...

      Private Function GetTrimmedArray(ByVal bytes() As Byte) As Byte()
        Dim index As Integer = bytes.Length
        Do
          index = index - 1
        Loop While index > -1 AndAlso bytes(index) = 0
        If index = -1 Then Return New Byte() {} ' all zeros
        Dim trimBytes(index) As Byte
        Buffer.BlockCopy(bytes, 0, trimBytes, 0, trimBytes.Length)
        Return trimBytes
      End Function
    

     

    • Marked as answer by Feanaro Monday, June 27, 2011 9:47 PM
    Monday, June 27, 2011 8:31 PM

All replies

  • So you want to trim the end of the byte array of 0s?

    Something like...

      Private Function GetTrimmedArray(ByVal bytes() As Byte) As Byte()
        Dim index As Integer = bytes.Length
        Do
          index = index - 1
        Loop While index > -1 AndAlso bytes(index) = 0
        If index = -1 Then Return New Byte() {} ' all zeros
        Dim trimBytes(index) As Byte
        Buffer.BlockCopy(bytes, 0, trimBytes, 0, trimBytes.Length)
        Return trimBytes
      End Function
    

     

    • Marked as answer by Feanaro Monday, June 27, 2011 9:47 PM
    Monday, June 27, 2011 8:31 PM
  • Can you not modify the function to return what you want? You will have to show us the function if you'd like us to look at it.

    --
    Andrew

    Monday, June 27, 2011 9:33 PM
  • Hey guys,

    I have a function that returns a byte(), the only problem is that the array most times is to long and has 4 or 5 excess null bytes. I want to remove them and tried everything, but I cant seem to find anything that works. Do you guys maybe know a solution to my problem? Thanks in advance.

    Feanaro

    I see you have marked an answer, but as Andrew alluded the real problem might be how the function sized the Byte() in the first place.

    Serial Port      Random      Microsoft® Community Contributor 2011
    Monday, June 27, 2011 11:19 PM