473,800 Members | 2,648 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Search a string buffer with nulls (chr(0))

!NoItAll
297 Contributor
I need to search a buffer for a string of characters.
The buffer is essentially a binary file (it's an image) and contains lots of chr(0) characters.
The string I need to locate also contains chr(0) characters. In fact it is the following string:
chr(100) & chr(0) & chr(0) & chr(163)

This is a marker in the image file for items I need to process.
So I though I would do the following:

Expand|Select|Wrap|Line Numbers
  1. Dim sFileBuffer as String  = system.io.file.readalltext("myimagefile")
  2. Dim sLookFor as String = chr(100) & chr(0) & chr(0) & chr(163)
  3.  
  4. Dim iLocation as Integer = sFileBuffer.IndexOf(sLookFor)
  5.  
The problem is that, although the characters in sLookFor definitely exist inside of sFileBuffer - IndexOf will always return -1 (not found).

I tried the following:

Expand|Select|Wrap|Line Numbers
  1. Dim Marker() as Byte = {100, 0, 0 , 163}
  2. Dim sLookFor as String = System.Text.Encoding.UTF8.GetString(Marker)
  3. Dim sFileBuffer as String  = system.io.file.readalltext("myimagefile",  Encoding.UTF8)
  4.  
  5. Dim iLocation as Integer = sFileBuffer.IndexOf(sLookFor)
  6.  
But this appears to only find occurrences of Chr(100) & Chr(0) - not the full 4 character sequence I desire. It appears to see the second Chr(0) as a termination of the search string.

I think the sticking point here is the null. Yes - I can string.replace( chr(0), Chr(255)) in both the sLookFor and the sFileBuffer and adjust my search accordingly - but that seems like a mess to me.

Is there not a way to search a buffer of binary data? I've tried working with byte arrays - but there appears to be no way to easily search for a sequence of byte values - just individual elements in the array.

VB6 did this perfectly just using strings.
Sep 25 '09 #1
11 5536
tlhintoq
3,525 Recognized Expert Specialist
I can't speak to VB6 doing this, but a string by definition is unicode terminated with a chr(0)
http://msdn.microsoft.com/en-us/libr...em.string.aspx
http://msdn.microsoft.com/en-us/libr...67(VS.85).aspx

So you have two issues:
1) your single bytes are being turned into two-byte unicode characters when the string is made, so your string no longer properly represents your bytes.
2) The first char(0) is the termination of the string
Sep 25 '09 #2
!NoItAll
297 Contributor
Ok - I will now answer my own question - and maybe someone will say - No - not that way dummy!
It appears that the way VB.NET stores strings is very different from the way VB6 did (DUH!). So reading a file into a string variable using file.readalltex t like this:

Dim MyFileData as String = System.IO.File. FeadAllText("my binaryfile.bin" )

encodes the data accurately, but differently than assigning characters to a string like:

Dim MySearchString as String = Chr(100) & Chr(0) & Chr(0) & Chr(163)

So you really will never find it using:

Dim iLocation as Integer = MyFileData.Inde xOf(MySearchStr ing)

This is because the data in MyFileData and MySearchString is not encoded the same way into their respective string variables.

Instead what you must do is make sure that both strings are encoded into the string variable identically. Do it this way:

Expand|Select|Wrap|Line Numbers
  1. Dim MySearchString as String = (Chr(100) & Chr(0) & Chr(0) & Chr(163)).Normalize
  2. Dim MyFileData as String = System.IO.File.ReadAllText("mybinaryfile.bin", Encoding.Default).Normalize
  3.  
  4. Dim iLocation as Integer = MyFileData.IndexOf(MySearchString)
  5.  
  6.  
This will return what you are looking for: binary data in the string variable. Both strings have been normalized to the same Unicode encoding scheme. There are options for the String.Normaliz e method - but you really don't care what they are as long as BOTH strings are encoded identically.

The Normalize method does the trick without mucking up your code.
Sep 25 '09 #3
!NoItAll
297 Contributor
@tlhintoq
Funny - I saw your response after I posted my solution. QA TLHO'
We are clearly on the same page - however it does appear that VB.NET strings can contain chr(0) characters and still be used (including those annoying little nulls) provided you are aware of how it is encoded. I'm not entirely sure exactly what VB.NET does with the ReadAllText method because I have to explicitly call ReadAllText("my binaryfile.bin" , Encoding.Defaul t). Apparently Encoding.Defaul t is not the default encoding used by ReadAllText, because if I fail to use the Encoding.Defaul t parameter my comparisons will fail - even though I String.Normaliz e the result.
In the end I think there are a lot of variables at play here and I've likely just come up with a relatively superficial solution. My goal was to keep the code simple and clean - avoiding making string copies all over the place.
I think, if I had a longer string to search for I would have to pay closer attention to how the String.Normaliz e method worked on it - I'm outa my league here though.

Des
Sep 25 '09 #4
tlhintoq
3,525 Recognized Expert Specialist
I personally think the real answer is to lot look for strings, don't convert to strings, don't muddle the data.

Why don't you want to just search the byte[] for the pattern you are looking for?
Sep 25 '09 #5
!NoItAll
297 Contributor
I would love to - but I have not found any way to search for a sequence of bytes in a byte array. All of the built-in .net functionality for searching in arrays is about finding single elements, not a sequence of elements.
Perhaps I've just not looked hard enough..
Sep 26 '09 #6
tlhintoq
3,525 Recognized Expert Specialist
All of the built-in .net functionality
built-in
Who said "built-in"? Make your own.

Loop through the target array looking for the first byte
Upon finding it, you loop through the rest of your comparrison array checking if each item matches. If you get through the entire comparator then you have a match.

Its just a loop with one nested loop inside.
Sep 26 '09 #7
!NoItAll
297 Contributor
I think it's a little more complicated then that - however I take your point and wrote the following comparison...
Now I did not spend a lot of time optimizing the code - and someone who knows better can probably reduce this a lot - however I need to keep two counters, one for loop for the main text and another for the text I'm looking for. All of this inside a Do Loop to iterate through the main text.
Frankly, this works much faster then I thought it would.
The stopwatch, however shows that the first time through the FindStrInArray it takes about 7 or 8 times longer than the simple string.indexof function.
However - the second time through it is about 3 times FASTER then the string.indexof function.

Now I know the exercise was about searching BINARY data and my example uses just text - however I have done all of the same things you must do for it to work with binary data - that is to explicity set the encoding on both the data I am searching and the data I am searching for. Of course you don't need to do this with the byte array.

If anyone wants to run this just create a form with a single button and paste this into your form code. Don't get fancy and rename the form or button...
You will need the declaration.txt file that is attached. It's read from the D: drive on my machine - you can put it anywhere you like.

Expand|Select|Wrap|Line Numbers
  1. Public Class Form1
  2.  
  3.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  4.  
  5.         Dim sDecl As String = System.IO.File.ReadAllText("d:\decli\Declaration.txt", System.Text.Encoding.Default).Normalize
  6.         Dim byteDecl() As Byte = System.IO.File.ReadAllBytes("d:\decli\Declaration.txt")
  7.         Dim sFindMe As String = ("abolishing the free System of English Laws").Normalize
  8.         Dim byteFindMe() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes("abolishing the free System of English Laws")
  9.         Dim iLocation As Integer = 0
  10.         Dim StopWatch As New System.Diagnostics.Stopwatch
  11.         'Which is faster?
  12.         'this
  13.  
  14.         StopWatch.Start()
  15.         iLocation = sDecl.IndexOf(sFindMe)
  16.         StopWatch.Stop()
  17.  
  18.         MsgBox(iLocation.ToString & Environment.NewLine & StopWatch.Elapsed.ToString)
  19.  
  20.         StopWatch.Reset()
  21.  
  22.         'reset ilocation
  23.         StopWatch.Start()
  24.         iLocation = FindStrInArray(byteDecl, byteFindMe)
  25.         StopWatch.Stop()
  26.  
  27.         MsgBox(iLocation.ToString & Environment.NewLine & StopWatch.Elapsed.ToString)
  28.  
  29.         StopWatch.Reset()
  30.         'or this
  31.  
  32.     End Sub
  33.     Friend Function FindStrInArray(ByVal LookIn() As Byte, ByVal Find() As Byte) As Integer
  34.  
  35.         Dim J As Integer = 1
  36.         Dim I As Integer = 0
  37.         Dim iLocation As Integer = 0
  38.  
  39.         Do While J < Find.Length
  40.             'find the first char
  41.             iLocation = Array.IndexOf(LookIn, Find(0), iLocation)
  42.             'if the first char was found then look for the rest
  43.             If iLocation > -1 Then
  44.                 iLocation += 1
  45.                 For I = iLocation To (iLocation + (Find.Length - 2))
  46.                     If LookIn(I) <> Find(J) Then
  47.                         J = 1    'return J to 0 since we have to start all over with the next occurance of the first char
  48.                         Continue Do
  49.                     End If
  50.                     J += 1
  51.                 Next
  52.                 Return (iLocation - 1)
  53.             Else
  54.                 'it was not found anywhere
  55.                 Exit Do
  56.             End If
  57.         Loop
  58.  
  59.         Return -1
  60.  
  61.     End Function
  62. End Class
  63.  
This was a fun exercise - but unless the loop-search function can be improved to work considerably faster than the string.indexof function then I'm not thinking its worth it. The loop is faster only when you call it multiple times to do the same thing - whereas the simpler approach is faster for each original call. And last, but certainly not least, the simpler call is just that, less code, cleaner and much easier to maintain - provided you understand the use and that each string must be explicitly encoded identically when you intend to do searches of binary data.
Attached Files
File Type: txt Declaration.txt (7.9 KB, 331 views)
Sep 26 '09 #8
tlhintoq
3,525 Recognized Expert Specialist
The stopwatch, however shows that the first time through the FindStrInArray it takes about 7 or 8 times longer than the simple string.indexof function.
However - the second time through it is about 3 times FASTER then the string.indexof function.
Take a good read through the MSDN of the Stopwatch class. The first use of a stopwatch (or the first use after it has not been used in a while) is not reliable.

One has to use the stopwatch, throw out those results. Then use it for real. Honest.
Sep 26 '09 #9
tlhintoq
3,525 Recognized Expert Specialist
Its just a loop with one nested loop inside.
I think it's a little more complicated then that
Here is a C# version of what I was suggesting. One loop inside another
Expand|Select|Wrap|Line Numbers
  1. // Returns the value of the NEXT byte after the match
  2. // Or -1 if no match
  3.         public int ReturnLocationAfterFound(byte[] SearchBytes, byte[] Targetbytes)
  4.         {
  5.             for (int a = 0; a < Targetbytes.Length; a++)
  6.             {
  7.                 // Search the length of the target array
  8.                 if (Targetbytes[a] == SearchBytes[0])
  9.                 {
  10.                     // We found a match to the first byte of our comparitor
  11.                     // Do all the rest match?
  12.                     for (int b = 0; b < SearchBytes.Length; b++)
  13.                     {
  14.                         bool WeHaveAWinner = false;
  15.                         if (Targetbytes[a + b] == SearchBytes[b])
  16.                         {
  17.                             WeHaveAWinner = true;// Keeps setting to true as long as they match
  18.                         }
  19.                         else
  20.                         {
  21.                             WeHaveAWinner = false;
  22.                             break;// break out of the 'b' loop since it doesn't match
  23.                         }
  24.                         if (WeHaveAWinner) return a + b;// this is the location right after our match
  25.                     }
  26.                 }
  27.             }
  28.             // If we got this far there was no match
  29.             return -1;
  30.         }
  31.  
  • The outter loop (the 'a' loop) is going through your big array one position at a time.
  • If a match is found to the first byte of your search pattern then it will fall into the inner loop (the 'b' loop)
  • From there it will check every byte of the search pattern in sequence to the next position of the big array.
  • If at any point they fail to match we break out of the inner loop, putting us back into the outter loop, moving on to the next byte of the big array.
  • If we get all the way through the inner loop, then we have a complete match and we return the next position after the matching section, since that is where you said you wanted to start processing.
Sep 26 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2643
by: Connelly Barnes | last post by:
Yet another useful code snippet! This StringBuffer class is a FIFO for character data. Example: B = StringBuffer('Hello W') B.append('orld!') print B.read(5) # 'Hello' print B.read() # 'World!'
1
5208
by: flam | last post by:
Hello, I am having a hard time spliting a string into an array for use in a search. Here is the situation. The user will input a search string. Normally I can just split the string by "split /\s+/, $string". However, I want to allow the user to put words so they appear and are searched together ie. "search this" would be searched as one term and not "search" and then somewhere else "this", etc. So if a user enters something like this:
1
36088
by: Ren? M?hle | last post by:
I have a psp script with a procedure just to run an update on one table. The Problem occurs when I try to compile this script with pspload: ORA-20006: "frsys_updatereport.psp": compilation failed with the following errors. ORA-06502: PL/SQL: numeric or value error: character string buffer too small Here the whole script:
1
2338
by: Srini | last post by:
Hi, I am working on a project and a portion of which involves receiving xml files on internet, extract values to build a string and pass that string to legacy system. I am planning on using XMLReader to read passed xml file and extract values that need to be mapped to string buffer. However, in this method I am not able to get the full path (ie., path information from root to this node)
2
1201
by: Bae,Hyun-jik | last post by:
Hi, My managed C++ library frequently takes LPCTSTR from managed exe. Due to the fact that my library doesn't modify string buffer if its parameter type is LPCTSTR, it won't be required to copy text data from System::String to another buffer memory, however, I couldn't find how to let my library access System::String text buffer directly. Please reply any answers. Thanks in advance.
3
5720
by: s88 | last post by:
Hello All: I'm trying to make a string buffer for my APIs. For example: void test(char * str){ sprintf(str,"inner test\n"); } int main(void){ int i = -5; char *str=(char*)malloc(sizeof(char)*100);
1
11702
by: atl10spro | last post by:
Hello Everyone, I am new to MS Access and although I have created several different databases I lack the VB knowledge to code a search function. I am turning to your expertise for assistance. I am using MS Access 2003. This is what I am looking for: A text field for the user to enter the search string or keyword.
8
4058
by: Zytan | last post by:
When using DllImport to import win32 functions that have strings, I know you can use the native c# string type. But, what about a function that expects a string buffer, and writes to it? I've seen people use StringBuilder for this, but is string good enough? The problem is that I am seeing what appears to be uninitialized data when I use StringBuilder, so I am wonder what is the correct solution thanks Zytan
5
2044
by: rsennat | last post by:
Hi, I'm having the following structures and std::list of that structs. I need to read the list of list as below and build a buffer as a table information. Any idea on how to build a table info (string buffer). list<NVPairsWithId> m_ResponseObj; struct NVPairsWithId {
0
9550
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10032
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7574
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5603
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2944
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.