Results 1 to 27 of 27

Thread: Check byte array for no value

  1. #1

    Thread Starter
    Lively Member Yumby's Avatar
    Join Date
    Feb 2009
    Posts
    120

    Check byte array for no value

    I'm trying to work out the following:

    dim myarray(1 to 5) as byte

    myarray(1) = "a"
    myarray(2) = "b"

    How do i check if myarray(3) has nothing in it?

    This is my first time working with byte arrays and from what I can work out, a byte array assigns a 0 (zero) to each variable when I declare the array. Therefore if it has something in it.... I can't work out how to check if it has nothing in it. How do I solve this? Thanks.

  2. #2
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: Check byte array for no value

    If you are going to assign string characters to an array, the array is declared As String, not As Byte
    Code:
    Dim myArray(1 to 5) As String
    myArray(1)="a"
    myArray(2)="b"
    If myArray(3) = vbNullString Then ' nothing assigned
    numeric arrays contain numeric values, string arrays contain string values
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  3. #3

    Thread Starter
    Lively Member Yumby's Avatar
    Join Date
    Feb 2009
    Posts
    120

    Re: Check byte array for no value

    Oh crap, sorry LaVolpe, no I'm putting hexadecimal values into the variables (myarray(1) = &HC0)

  4. #4
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: Check byte array for no value

    Then you have no way of knowing whether the array item has been assigned or not because a valid value is &H0

    You may need to use a 2D array where 1D is for the values and the 2D is a 1 or 0 indicating value has been assigned. Other tracking mechanisms could work, including using an integer array and using the high byte to determine whether or not assignment made. 1D array of Integers = same size as 2D array of bytes
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  5. #5
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Check byte array for no value

    You could also use a Variant array. Unassigned Variants default to Empty if I remembered correctly.

    I prefer LaVolpe's suggestion though. Variants are slower and bigger. A whopping 16 bytes! You'd be wasting 15 bytes per byte.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  6. #6

    Thread Starter
    Lively Member Yumby's Avatar
    Join Date
    Feb 2009
    Posts
    120

    Re: Check byte array for no value

    Your 2D array theory has got me thinking, I could just use a counter.....

    Code:
    myarray(1) = &HC0
    numbervalue = numbervalue + 1
    myarray(2) = &HC0
    numbervalue = numbervalue + 1
    And then...
    Code:
    for x = 0 to numbervalue
    etc
    next x
    I think that's the easiest (and probably the ugliest) solution for me.

  7. #7
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: Check byte array for no value

    Counter theory has potential error problems: Byte value cannot exceed 255 & limits your counter to 255 else error
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  8. #8

    Thread Starter
    Lively Member Yumby's Avatar
    Join Date
    Feb 2009
    Posts
    120

    Re: Check byte array for no value

    Unassigned Variants default to Empty if I remembered correctly
    Yeah, from what I read recently, that' s right. And therefore, I could use the isempty function. I avoided it because I thought there might be problems with it in the future. I'll give it a try, yeah it's a waste of bytes but that thankfully is not an issue. Thanks guys!

  9. #9

    Thread Starter
    Lively Member Yumby's Avatar
    Join Date
    Feb 2009
    Posts
    120

    Re: Check byte array for no value

    Counter theory has potential error problems: Byte value cannot exceed 255 & limits your counter to 255 else error
    Yeah that's okay. Maybe not 100% professional, but it's very clear in my mind that I'm working within the 0 to 255 range. Thanks.

  10. #10
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Check byte array for no value

    Quote Originally Posted by Yumby View Post
    I avoided it because I thought there might be problems with it in the future.
    The only problem is that its a Variant.....it can be assigned any kind of value, Bytes, Booleans, TextBoxes. You'd have to be extra responsible. You can use VarType(I think??) to make sure the Variant's sub-type is Byte and throw an error if its not. It should help somewhat if you're ever complacent and assign a value greater than 255 or anything that is not a Byte.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  11. #11
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,582

    Re: Check byte array for no value

    Quote Originally Posted by Yumby View Post
    Your 2D array theory has got me thinking, I could just use a counter.....

    Code:
    myarray(1) = &HC0
    numbervalue = numbervalue + 1
    myarray(2) = &HC0
    numbervalue = numbervalue + 1
    And then...
    Code:
    for x = 0 to numbervalue
    etc
    next x
    I think that's the easiest (and probably the ugliest) solution for me.
    Quote Originally Posted by LaVolpe View Post
    Counter theory has potential error problems: Byte value cannot exceed 255 & limits your counter to 255 else error
    Why would the counter (essentially the length of the amount of the byte array that has been used) be limited to 255?
    I use byte arrays of hundreds of thousands of bytes as buffers, and a counter to track how much has been filled and needs to be transmitted or processed. The counter doesn't need to be a byte type just because you have an array of bytes.

  12. #12
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Check byte array for no value

    Some sort of "number of bytes used" counter should be fine, or if 0 is never a valid value you could also use that as a marker for the end of used space.

    Both of these break down if the array is used sparsely rather than cumulatively though.

  13. #13
    Hyperactive Member
    Join Date
    Jun 2011
    Posts
    461

    Re: Check byte array for no value

    I've tried with &HC0 and this is the result:
    VB Code:
    1. Dim myArray(1) As Byte
    2. myArray(0) = &HC0
    3. MsgBox myArray(0) = vbEmpty 'Returns False
    4. MsgBox myArray(1) = vbEmpty 'Returns True
    But like others said above, for &H0 there is no way how to directly test if it's already assigned to the some element or not - because it's the null/default value.
    Last edited by MikiSoft; Apr 18th, 2015 at 06:26 AM.

  14. #14
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Check byte array for no value

    Yes, but this has no significance. It misleadingly abuses the constant, which has no meaning in this context.

    vbEmpty just happens to be equal to 0.

  15. #15
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: Check byte array for no value

    If the goal is to determine the next item in the array to populate, then a counter is fine. Such logic is used so often

    If the goal is to determine whether or not a value has been assigned to a specific array item, then a counter will not help. In that case an Integer array can be useful. When assigning an array item, OR it with 256. That way, any array item that is exactly zero will not have been assigned a value yet. To retrieve the actual value of the array item, AND it with 255. To clear the assignment, simply set it back to 0. Erasing the array resets all back to unassigned.
    Code:
    myArray(10) = &H7 Or &H100 ' (256)
    If myArray(10) <> 0 Then ' else nothing assigned to that array item 
        MsgBox myArray(10) And &HFF
    End If
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  16. #16
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Check byte array for no value

    Quote Originally Posted by LaVolpe View Post
    If the goal is to determine the next item in the array to populate, then a counter is fine. Such logic is used so often

    If the goal is to determine whether or not a value has been assigned to a specific array item, then a counter will not help. In that case an Integer array can be useful. When assigning an array item, OR it with 256. That way, any array item that is exactly zero will not have been assigned a value yet. To retrieve the actual value of the array item, AND it with 255. To clear the assignment, simply set it back to 0. Erasing the array resets all back to unassigned.
    Code:
    myArray(10) = &H7 Or &H100 ' (256)
    If myArray(10) <> 0 Then ' else nothing assigned to that array item 
        MsgBox myArray(10) And &HFF
    End If
    This is by far the best solution. Partly because its the fastest. The CPU itself has instructions for bitwise operations, not to mention Integer operations are also native CPU capabilities.

    This solution is also type safe, much more so than the Variant solution.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  17. #17
    Frenzied Member
    Join Date
    Dec 2012
    Posts
    1,470

    Re: Check byte array for no value

    This is what I use:
    Code:
    Private Function GetbSize(bArray() As Byte) As Long
        On Error GoTo GetSizeErr
        GetbSize = UBound(bArray) + 1
        Exit Function
    GetSizeErr:
        GetbSize = 0
    End Function
    It falsely returns 0 for a NULL array, but the theory is that if it is a single element array, you would not be using an array anyway. You could just as easily return -1 as long as your receiving code reacts accordingly.

    J.A. Coutts

  18. #18
    PowerPoster
    Join Date
    Jun 2013
    Posts
    7,219

    Re: Check byte array for no value

    Quote Originally Posted by couttsj View Post
    This is what I use:
    Code:
    Private Function GetbSize(bArray() As Byte) As Long
        On Error GoTo GetSizeErr
        GetbSize = UBound(bArray) + 1
        Exit Function
    GetSizeErr:
        GetbSize = 0
    End Function
    This routine would return incorrect sizes for any LBounds which differ from Zero...

    You might want to correct this function to:
    Code:
    Private Function GetbSize(bArray() As Byte) As Long
    On Error GoTo ExitWithZero
        GetbSize = UBound(bArray) - LBound(bArray) + 1
    ExitWithZero:
    End Function
    Olaf

  19. #19
    Frenzied Member
    Join Date
    Dec 2012
    Posts
    1,470

    Re: Check byte array for no value

    Quote Originally Posted by Schmidt View Post
    This routine would return incorrect sizes for any LBounds which differ from Zero...
    Olaf
    I used to use both zero based and one based arrays, but it got to be very confusing and I wasted a lot of time troubleshooting. I only use zero based arrays now.

    J.A. Coutts

  20. #20
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: Check byte array for no value

    Quote Originally Posted by Schmidt View Post
    You might want to correct this function to:
    Code:
    Private Function GetbSize(bArray() As Byte) As Long
    On Error GoTo ExitWithZero
        GetbSize = UBound(bArray) - LBound(bArray) + 1
    ExitWithZero:
    End Function
    And if you want to be completely safe, probably should test for UBound < LBound as can happen when VB tries to tell you array is 'invalid', i.e.,
    Code:
    Dim arrString() As String, sData As String
    arrStrings() = Split(sData, ",")
    MsgBox LBound(arrStrings) & " to " & UBound(arrStrings)
    But the last few posts have been off-topic I believe. The OP didn't seem to need to determine if any array is initialized or not, especially since his original post used a static array

    Edited. Yes my sample was with string arrays, but Byte arrays can be sized same way
    Code:
    Dim b() As Byte, sData As String
    b() = StrConv(sData, vbFromUnicode)
    Last edited by LaVolpe; Apr 20th, 2015 at 06:55 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  21. #21
    PowerPoster
    Join Date
    Jun 2013
    Posts
    7,219

    Re: Check byte array for no value

    Quote Originally Posted by LaVolpe View Post
    And if you want to be completely safe, probably should test for UBound < LBound as can happen when VB tries to tell you array is 'invalid', i.e.,
    No, such a test is not necessary, since the case is completely covered by:
    UBound(Arr) - LBound(Arr) + 1 (not triggering any error then)

    The "0 to -1" case is just a SafeArray which is already initialized, but (yet) without any Elements
    (the LBound Members at Zero, the ElementsCount-Members too).

    Since a SafeArray-Struct doesn't contain a UBound-Member - the developers of
    of VBs UBound-Implementation return simply: LBound + ElementCount - 1
    (that's where the "weird" -1 comes from).

    Olaf

  22. #22
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Check byte array for no value

    Wait a second...if I remembered correctly, doesn't Ubound throw an error when used on a array that has no elements ?

    I remember having to use On Error statements to check for empty arrays.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  23. #23
    PowerPoster
    Join Date
    Jun 2013
    Posts
    7,219

    Re: Check byte array for no value

    Quote Originally Posted by Niya View Post
    Wait a second...if I remembered correctly, doesn't Ubound throw an error when used on a array that has no elements ?

    I remember having to use On Error statements to check for empty arrays.
    The On Error Check (as in the small routine I've posted) is necessary *only*
    for VB-Array-Variables, which are completely uninitialized (have an ArrPtr of Zero,
    aka: no SafeArray-Struct assigned yet).

    What I just described, differs from the case LaVolpe pointed out.

    He was talking about an *initialized* array like below, which got a SafeArray-Struct assigned, but contains no Elements:

    Code:
    Dim B() As Byte
        B = vbNullString 'assigns a SafeArray-Struct, but with an ElementCount of Zero (LBound=0, Ubound=-1)
    But I agree with LaVolpe, that this is not really OnTopic in this thread - just wanted to point out
    a potential Error-Source to couttsj, in case he's using the routine he posted in "shipped Binaries".

    Olaf

  24. #24
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Check byte array for no value

    Quote Originally Posted by Schmidt View Post
    He was talking about an *initialized* array like below, which got a SafeArray-Struct assigned, but contains no Elements:

    Code:
    Dim B() As Byte
        B = vbNullString 'assigns a SafeArray-Struct, but with an ElementCount of Zero (LBound=0, Ubound=-1)
    Wow, how did I never know this. Do you know how much headaches this would have saved me. Granted its a hacky way to get UBound to work correctly on empty arrays but its preferable to error checking.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  25. #25
    PowerPoster
    Join Date
    Feb 2015
    Posts
    2,671

    Re: Check byte array for no value

    This is fast way to determine a empty array:
    Code:
    ' Declare only in a standart module !
    
    Public Function ArrInit(ByVal lpArr As Long) As Long
        Dim inide   As Boolean  '<- isn't in exe
        
        ArrInit = lpArr
        
        ' <----------------- not compile -------------------+
                                                        '   |
        Debug.Assert MakeTrue(inide)                    '   |
                                                        '   |
        If inide Then RemoveIDEBug                      '   |
                                                        '   |
    End Function                                        '   |
                                                        '   |
    Private Sub RemoveIDEBug()                          '   |
        On Error Resume Next                            '   |
        Debug.Assert 5 / 1                              '   |
    End Sub                                             '   |
                                                        '   |
    Private Function MakeTrue(bool As Boolean) As Long  '   |
        MakeTrue = True                                 '   |
        bool = True                                     '   |
    End Function                                        '   |
                                                        '   |
        ' <----------------- not compile -------------------+
    Use:
    Code:
    Private Sub Form_Load()
        Dim B() As Byte
    
        MsgBox ArrInit(Not Not B)
        
        ReDim B(5)
        
        MsgBox ArrInit(Not Not B)
        
        Erase B
        
        MsgBox ArrInit(Not Not B)
        
    End Sub
    Assembler listing:

  26. #26
    PowerPoster
    Join Date
    Jun 2013
    Posts
    7,219

    Re: Check byte array for no value

    Quote Originally Posted by The trick View Post
    This is fast way to determine a empty array:
    It is quite fast - but why has a check for a correctly initialized Array be faster than,
    say, ... 0.2µsec (Micro-, not Milliseconds), ... as is achievable with this function:

    Code:
    Public Function IsDimmed(Arr As Variant) As Boolean
    On Error GoTo ReturnFalse
      IsDimmed = UBound(Arr) >= LBound(Arr)
    ReturnFalse:
    End Function
    And that those Not Not Checks are error-prone is well-known...

    And all those "InIde-Debug.Assert-Solutions" will definitely *not*
    remove the destructive behaviour of Not Not Array, with:

    Error 16 (Expression too complex)

    ...when the Binary in question is e.g. compiled to P-Code (there's a lot of Developers out there,
    which prefer this option at least for their GUI-Code, because it produces smaller Binaries).

    To reproduce that, one can use your Helper-routines in a *.bas-Module, and
    then put the code below into a Form, compile to P-Code, run the Exe and click the Form:

    Code:
    Option Explicit
     
    Private Sub Form_Click()
    
        Dim Arr() As Byte
     
        MsgBox ArrInit(Not Not Arr)
        
        ReDim Arr(5)
        
        MsgBox ArrInit(Not Not Arr)
        
        Erase Arr
        
        MsgBox ArrInit(Not Not Arr)
        
        MsgBox 4 / 2 'will cause Error 16
        
    End Sub
    Olaf

  27. #27

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width