Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys, os
- from PyQt4 import Qt, QtGui, QtCore
- import binascii
- import re
- class MainWindow( QtGui.QMainWindow ):
- width = 640
- height = 480
- def __init__( self ):
- QtGui.QMainWindow.__init__( self )
- self.setWindowTitle( "Binary & Ascii Converter" )
- main = QtGui.QWidget()
- vbox = QtGui.QVBoxLayout()
- hbox = QtGui.QHBoxLayout()
- self.text = QtGui.QTextEdit( self )
- self.label = QtGui.QTextEdit( self )
- self.label.setReadOnly( True )
- self.label.setStyleSheet( "background-color: rgb( 0, 0, 0 ); color: rgb( 255, 255, 255 );" )
- btnBinary = QtGui.QPushButton( 'To Binary', self )
- btnAscii = QtGui.QPushButton( 'To Ascii', self )
- hbox.addWidget( btnBinary )
- hbox.addWidget( btnAscii )
- vbox.addWidget( self.text )
- vbox.addWidget( self.label )
- vbox.addLayout( hbox )
- main.setLayout( vbox )
- self.setCentralWidget( main )
- self.resize( MainWindow.width, MainWindow.height )
- self.center()
- self.statusBar().showMessage( 'Ready' )
- self.connect( btnBinary, QtCore.SIGNAL( 'clicked()' ), self.toBinary )
- self.connect( btnAscii, QtCore.SIGNAL( 'clicked()' ), self.toAscii )
- def toBinaryHardWay( self ):
- out = ""
- b = bytearray( str( self.text.toPlainText() ) )
- for i in b:
- val = i
- for ii in xrange( 8 ):
- out += "0" if ( val & 128 ) == 0 else "1"
- val <<= 1
- out += " "
- print out
- def toBinary( self ):
- try:
- out = bin( int( binascii.hexlify( str( self.text.toPlainText() ) ), 16 ) ).replace( "b", "" )
- out = re.sub( "(.{8})", "\\1\n", out, re.DOTALL )
- self.statusBar().showMessage( 'Ascii data succesfully converted to binary' )
- self.label.setText( out )
- except:
- self.statusBar().showMessage( 'Error: Invalid data entered, please ensure that the information is correct and try again' )
- self.label.setText( self.text.toPlainText() )
- def toAscii( self ):
- try:
- n = int( str( self.text.toPlainText().replace( "\n", "" ) ), 2 )
- out = binascii.unhexlify( '%x' % n )
- self.statusBar().showMessage( 'Binary data succesfully converted to ascii' )
- self.label.setText( out )
- except:
- self.statusBar().showMessage( 'Error: Data is not binary, please check your input and try again' )
- self.label.setText( self.text.toPlainText() )
- def center( self ):
- screen = QtGui.QDesktopWidget().screenGeometry()
- size = self.geometry()
- widthDif = screen.width() - size.width()
- heightDif = screen.height() - size.height()
- x = widthDif / 2
- y = heightDif / 2
- self.move( x, y )
- def main():
- app = QtGui.QApplication( sys.argv );
- window = MainWindow();
- window.show();
- sys.exit( app.exec_() )
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement