Merge branch 'RfidResearchGroup:master' into spi_flash_v2
[RRG-proxmark3.git] / tools / findbits.py
bloba2c8342b74e2f2253a8ba11be3bb25ca969428ad
1 #!/usr/bin/env python3
3 # findbits.py - find Binary, Octal, Decimal or Hex number in bitstream
5 # Adam Laurie <adam@algroup.co.uk>
6 # http://rfidiot.org/
8 # This code is copyright (c) Adam Laurie, 2009, All rights reserved.
9 # For non-commercial use only, the following terms apply - for all other
10 # uses, please contact the author:
12 # This code is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
17 # This code is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
23 import sys
24 import os
26 # invert binary string
27 def invert(data):
28 return ''.join('0' if c == '1' else '1' for c in data)
30 # do the actual search
31 def search(target,data):
32 location = data.find(target)
33 if location >= 0:
34 print('*** Match at bit {:d}: {}<{}>{}'.format(location, data[:location],target,data[location+len(target):]))
35 else:
36 print('Not found')
38 # convert integer to binary string
39 def binstring(number):
40 return bin(number)[2:] if number > 0 else ''
42 # reverse string order
43 def stringreverse(data):
44 return data[::-1]
46 # match forward, backward and inverted
47 def domatch(binary,number):
48 reversed= stringreverse(number)
49 inverted= invert(binary)
51 print(' Forward: (%s) ' % number, end = '')
52 search(binary,number)
53 print(' Reverse: (%s) ' % reversed, end = '')
54 search(binary,reversed)
55 print(' Inverse: (%s) ' % inverted)
56 print(' Forward: (%s) ' % number, end = '')
57 search(inverted,number)
58 print(' Reverse: (%s) ' % reversed, end = '')
59 search(inverted,reversed)
61 def main():
62 if(len(sys.argv) < 3):
63 print("""
64 \t{0} - Search bitstream for a known number
66 Usage: {0} <NUMBER> <BITSTREAM>
68 \tNUMBER will be converted to its BINARY equivalent for all valid
69 \tinstances of BINARY, OCTAL, DECIMAL and HEX, and the bitstream
70 \tand its inverse will be searched for a pattern match. Note that
71 \tNUMBER must be specified in BINARY to match leading zeros.
73 Example:
75 \t{0} 73 0110010101110011
76 """.format(sys.argv[0]))
77 os._exit(True)
79 bases= {
80 2:'BINARY',
81 8:'OCTAL',
82 10:'DECIMAL',
83 16:'HEX',
86 for base, base_name in sorted(bases.items()):
87 try:
88 number= int(sys.argv[1],base)
89 print('\nTrying ' + base_name)
90 # do BINARY as specified to preserve leading zeros
91 if base == 2:
92 domatch(sys.argv[1],sys.argv[2])
93 else:
94 domatch(binstring(number),sys.argv[2])
95 except:
96 continue
98 if __name__ == '__main__':
99 main()