Python Print Hex variable - python

I have hex variable that I want to print as hex
data = '\x99\x02'
print (data)
Result is: ™
I want to the python to print 0x9902
Thank you for your help

Please check this one.
data = r'\x99\x02'
a, b = [ x for x in data.split(r'\x') if x]
d = int(a+b, base=16)
print('%#x'%d)

You have to convert every char to its number - ord(char) - and convert every number to hex value - '{:02x}'.format() - and concatenate these values to string. And add string '0x'.
data = '\x99\x02'
print('0x' + ''.join('{:02x}'.format(ord(char)) for char in data))
EDIT: The same but first string is converted to bytes using encode('raw_unicode_escape')
data = '\x99\x02'
print('0x' + ''.join('{:02x}'.format(code) for code in data.encode('raw_unicode_escape')))
and if you have already bytes then you don't have to encode()
data = b'\x99\x02'
print('0x' + ''.join('{:02x}'.format(code) for code in data))
BTW: Similar way you can convert to binary using {:08b}
data = '\x99\x02'
print(''.join('{:08b}'.format(code) for code in data.encode('raw_unicode_escape')))

Related

Formatting strings with integers

I'm trying to increment the video file names every time they get into my folder. I tried the + and the join() method but I can't seem to figure it out. I tried integers without quotation marks but the join method wont let me use an integer so I tried with quotation marks but now it won't increment
Here is my code
VideoNumber += "99"
folderLocation = ("C:/Users/someone/Documents", VideoNumber, ".mp4")
x = "/".join(folderLocation)
print(x)
You can format integers into a string using an f-string or the format() method on strings.
video_number += 99
video_path = f"C:/Users/someone/Documents/{video_number}.mp4"
print(video_path)
Just as an example of how to make your original code work, you could keep your number as an integer and then convert it to a string using str() (though note this has a bug because you will have an extra / between the number and .mp4).
VideoNumber += 99
folderLocation = ("C:/Users/someone/Documents", str(VideoNumber), ".mp4")
x = "/".join(folderLocation)
print(x)
You can cast the integer into string, so your code will be like this
folderLocation = ("C:/Users/someone/Documents", str(VideoNumber), ".mp4")

How to convert Binary to Strings?

I am currently working on a binary encryption code: [Sender(Msg Input=> Binary Conversion)] : [Receiver (Binary Conversion => Msg Output)]
As of now I am able to convert text based Msgs , e.g) How are you? etc.
print("Enter Msg:")
def Binary_Encryption(message):
message = ''.join(format(i, 'b') for i in bytearray(message, encoding ='utf-8'))
print(message)
Binary_Encryption(input("").replace (" ","\\"))
Output: 10010001101111111011110111001100001111001011001011011100111100111011111110101111111
After the binary string is obtained, by just copying the string and placing it within this block of code will decrypt it.
def Binary_Decryption(binary):
string = int(binary, 2)
return string
bin_data = (input("Enter Binary:\n"))
str_data =''
for i in range(0, len(bin_data), 7):
temp_data = bin_data[i:i + 7]
decimal_data = Binary_Decryption(temp_data)
str_data = str_data + chr(decimal_data)
print("Decrypted Text:\n"+str_data.replace("\\"," "))
Output: How are you?
But I am not able to convert a certain inputs , e.g) ?? , 8879 , Oh! How are You? etc.
basically the msgs that are not being converted are Msgs with multiple uses of numbers or special
characters.
Msg Input for ?? gives "⌂▼" and 8879 gives "qc?☺" while Oh! How are You? gives "OhC9◄_o9CeK93_k▼
I think the problem is that the special characters (!, ?) contains only 6 bits, while the other characters 7.This messes things up if there are other characters behind the special one I think. Maybe something like this should work. There is probably a better way to solve this though.
def Binary_Encryption(message):
s = ""
for i in bytearray(message, encoding="utf-8"):
c = format(i, "b")
addon = 7 - len(c)
c = addon * "0" + c # prepend 0 if len shorter than 7
s += c # Add to string
print(s)
Your problem is that you are copying the output from binary_encrypt directly which truncate leading zeros so 8 instead of being 00111000 it became 111000 which result in 2 bits being used from next ASCII binary character since ASCII characters are represented as 8-bits values to print number 8897 use0011100000111000001110010011011100001010 as input to binary_decrypt. look for ASCII table to see the binary equivalents for each character.Just edit your code like this.
print("Enter Msg:")
def Binary_Encryption(message):
# pass 08b to format
message = ''.join(format(i, '08b') for i in bytearray(message, encoding ='utf-8'))
print(message)
Binary_Encryption(input("").replace (" ","\\"))

Convert String to hex and send via serial in Python

I want to convert the string 400AM49L01 to a hexadecimal form (and then into bytes) b'x\34\x30\x30\x41\x4d\x34\x39\x4c\x30', so I can write it with pySerial.
I already tried to convert the elements of a list, which contains the single hexadecimals like 0x31 (equals 4), into bytes, but this will result in b'400AM49L01'.
device = '400AM49L01'
device = device.encode()
device = bytes(device)
device = str(binascii.hexlify(device), 'ascii')
code = '0x'
text = []
count = 0
for i in device:
if count % 2 == 0 and count != 0:
text.append(code)
code = '0x'
count = 0
code += i
count += 1
text.append((code))
result = bytes([int(x, 0) for x in text])
Really looking forward for your help!
The following code will give the result you expecting.
my_str = '400AM49L01'
"".join(hex(ord(c)) for c in my_str).encode()
# Output
# '0x340x300x300x410x4d0x340x390x4c0x300x31'
What is it doing ?
In order to convert a string to hex, you need to convert each character to the integer value from the ascii table using ord().
Convert each int value to hex using the function hex().
Concatenate all hex value generated using join().
Encode the str to bytes using .encode().
Regards!

Python3 print in hex representation

I can find lot's of threads that tell me how to convert values to and from hex. I do not want to convert anything. Rather I want to print the bytes I already have in hex representation, e.g.
byteval = '\x60'.encode('ASCII')
print(byteval) # b'\x60'
Instead when I do this I get:
byteval = '\x60'.encode('ASCII')
print(byteval) # b'`'
Because ` is the ASCII character that my byte corresponds to.
To clarify: type(byteval) is bytes, not string.
>>> print("b'" + ''.join('\\x{:02x}'.format(x) for x in byteval) + "'")
b'\x60'
See this:
hexify = lambda s: [hex(ord(i)) for i in list(str(s))]
And
print(hexify("abcde"))
# ['0x61', '0x62', '0x63', '0x64', '0x65']
Another example:
byteval='\x60'.encode('ASCII')
hexify = lambda s: [hex(ord(i)) for i in list(str(s))]
print(hexify(byteval))
# ['0x62', '0x27', '0x60', '0x27']
Taken from https://helloacm.com/one-line-python-lambda-function-to-hexify-a-string-data-converting-ascii-code-to-hexadecimal/

Unpacking a struct ending with an ASCIIZ string

I am trying to use struct.unpack() to take apart a data record that ends with an ASCII string.
The record (it happens to be a TomTom ov2 record) has this format (stored little-endian):
1 byte
4 byte int for total record size (including this field)
4 byte int
4 byte int
variable-length string, null-terminated
unpack() requires that the string's length be included in the format you pass it. I can use the second field and the known size of the rest of the record -- 13 bytes -- to get the string length:
str_len = struct.unpack("<xi", record[:5])[0] - 13
fmt = "<biii{0}s".format(str_len)
then proceed with the full unpacking, but since the string is null-terminated, I really wish unpack() would do it for me. It'd also be nice to have this should I run across a struct that doesn't include its own size.
How can I make that happen?
I made two new functions that should be useable as drop-in replacements for the standard pack and unpack functions. They both support the 'z' character to pack/unpack an ASCIIZ string. There are no restrictions to the location or number of occurrences of the 'z' character in the format string:
import struct
def unpack (format, buffer) :
while True :
pos = format.find ('z')
if pos < 0 :
break
asciiz_start = struct.calcsize (format[:pos])
asciiz_len = buffer[asciiz_start:].find('\0')
format = '%s%dsx%s' % (format[:pos], asciiz_len, format[pos+1:])
return struct.unpack (format, buffer)
def pack (format, *args) :
new_format = ''
arg_number = 0
for c in format :
if c == 'z' :
new_format += '%ds' % (len(args[arg_number])+1)
arg_number += 1
else :
new_format += c
if c in 'cbB?hHiIlLqQfdspP' :
arg_number += 1
return struct.pack (new_format, *args)
Here's an example of how to use them:
>>> from struct_z import pack, unpack
>>> line = pack ('<izizi', 1, 'Hello', 2, ' world!', 3)
>>> print line.encode('hex')
0100000048656c6c6f000200000020776f726c64210003000000
>>> print unpack ('<izizi',line)
(1, 'Hello', 2, ' world!', 3)
>>>
The size-less record is fairly easy to handle, actually, since struct.calcsize() will tell you the length it expects. You can use that and the actual length of the data to construct a new format string for unpack() that includes the correct string length.
This function is just a wrapper for unpack(), allowing a new format character in the last position that will drop the terminal NUL:
import struct
def unpack_with_final_asciiz(fmt, dat):
"""
Unpack binary data, handling a null-terminated string at the end
(and only at the end) automatically.
The first argument, fmt, is a struct.unpack() format string with the
following modfications:
If fmt's last character is 'z', the returned string will drop the NUL.
If it is 's' with no length, the string including NUL will be returned.
If it is 's' with a length, behavior is identical to normal unpack().
"""
# Just pass on if no special behavior is required
if fmt[-1] not in ('z', 's') or (fmt[-1] == 's' and fmt[-2].isdigit()):
return struct.unpack(fmt, dat)
# Use format string to get size of contained string and rest of record
non_str_len = struct.calcsize(fmt[:-1])
str_len = len(dat) - non_str_len
# Set up new format string
# If passed 'z', treat terminating NUL as a "pad byte"
if fmt[-1] == 'z':
str_fmt = "{0}sx".format(str_len - 1)
else:
str_fmt = "{0}s".format(str_len)
new_fmt = fmt[:-1] + str_fmt
return struct.unpack(new_fmt, dat)
>>> dat = b'\x02\x1e\x00\x00\x00z\x8eJ\x00\xb1\x7f\x03\x00Down by the river\x00'
>>> unpack_with_final_asciiz("<biiiz", dat)
(2, 30, 4886138, 229297, b'Down by the river')

Categories

Resources