Problem in executing code to convert hexadecimal to decimal - python

I have this problem:
n = int(input("Enter Hexadecimal Number: ")
print(0xn)
I found that it works when n is already defined...
Also how to convert it when the number is a string like 2ABF

The 0b, 0o, and 0x modifiers only work with int literals, by which I mean, when you're writing the integer literally in code. You can't simply apply them to a variable that already has a value, as integers aren't stored with any particular base in mind (that only matters when you display them somehow).
When converting a string to an int, you can specify the base it's in as a second argument:
n = int("AF", 16)
# 175
For bases beyond 16, it continues to use the rest of the alphabet, up to 36, after which point it refuses to continue because there are no more letters, forcing you to write your own.
When converting an int to a string, there's no particular one-size-fits-all method. However, for the common bases in particular, there are built-in functions:
bin(n) # '0b10101111' - base 2
oct(n) # '0o257' - base 8
hex(n) # '0xaf' - base 16
You can then do the usual string manipulation on these to get rid of the first two characters and make the hex all-uppercase, if you want:
print(hex(n)[2:].upper())
# AF

Try as follow:
n = input("Enter Hexadecimal Number: ")
print(hex(int('0x' + n, 16)))

Related

python how convert a binary string to a binary number [duplicate]

I can't quite find a solution for this.
Basically what I've done so far is created a string which represents the binary version of x amount of characters padded to show all 8 bits.
E.g. if x = 2 then I have 0101100110010001 so 8 digits in total. Now I have 2 strings of the same length which I want to XOR together, but python keeps thinking it's a string instead of binary. If I use bin() then it throws a wobbly thinking it's a string which it is. So if I cast to an int it then removes the leading 0's.
So I've already got the binary representation of what I'm after, I just need to let python know it's binary, any suggestions?
The current function I'm using to create my binary string is here
for i in origAsci:
origBin = origBin + '{0:08b}'.format(i)
Thanks in advance!
Use Python's int() function to convert the string to an integer. Use 2 for the base parameter since binary uses base 2:
binary_str = '10010110' # Binary string
num = int(binary_str, 2)
# Output: 150
Next, use the bin() function to convert the integer to binary:
binary_num = bin(num)
# Output: 0b10010110

Python convert a string containing hex to actual hex

I have a hex string, but i need to convert it to actual hex.
For example, i have this hex string:
3f4800003f480000
One way I could achieve my goal is by using escape sequences:
print("\x3f\x48\x00\x00\x3f\x48\x00\x00")
However, I can't do it this way, because I want create together my hex from multiple variables.
My program's purpose is to:
take in a number for instance 100
multiply it by 100: 100 * 100 = 10000
convert it to hex 2710
add 0000
add 2710 again
add 0000 once more
Result I'm expecting is 2710000027100000. Now I need to pass this hexadecimal number as argument to a function (as hexadecimal).
In Python, there is no separate type as 'hex'. It represents the hexadecimal notation of the number as str. You may check the type yourself by calling it on hex() as:
# v convert integer to hex
>>> type(hex(123))
<type 'str'>
But in order to represent the value as a hexadecimal, Python prepends the 0x to the string which represents hexadecimal number. For example:
>>> hex(123)
'0x7b'
So, in your case in order to display your string as a hexadecimal equivalent, all you need is to prepend it with "0x" as:
>>> my_hex = "0x" + "3f4800003f480000"
This way if you probably want to later convert it into some other notation, let's say integer (which based on the nature of your problem statement, you'll definitely need), all you need to do is call int with base 16 as:
>>> int("0x3f4800003f480000", base=16)
4559894623774310400
In fact Python's interpreter is smart enough. If you won't even prepend "0x", it will take care of it. For example:
>>> int("3f4800003f480000", base=16)
4559894623774310400
"0x" is all about representing the string is hexadecimal string in case someone is looking/debugging your code (in future), they'll get the idea. That's why it is preferred.
So my suggestion is to stick with Python's Hex styling, and don't convert it with escape characters as "\x3f\x48\x00\x00\x3f\x48\x00\x00"
From the Python's hex document :
Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If x is not a Python int object, it has to define an index() method that returns an integer.
try binascii.unhexlify:
Return the binary data represented by the hexadecimal string hexstr.
example:
assert binascii.unhexlify('3f4800003f480000') == b"\x3f\x48\x00\x00\x3f\x48\x00\x00"
>>> hex(int('3f4800003f480000', 16))
'0x3f4800003f480000'

Taking the exponent of a SHA3 hash function

I am trying to implement a protocol described in the paper Private Data Aggregation with Groups for Smart Grids in a Dynamic Setting using CRT in python.
In order to do this, I need to calculate the following value:
I know that since python 3.6, you can calculate a SHA3 value as follows:
import hashlib
hash_object = hashlib.sha3_512(b'value_to_encode')
hash_value = hash_object.hexdigest()
I was wondering you should solve this, since, as far as I know, a SHA-3 function returns a string and therefore cannot be calculated in a function with to the power of n.
What am I overlooking?
If we define a hash function $H: \{0, 1\}^* \rightarrow \{0, 1\}^n$, that is one that produces an $n$ bit output, we can always interpret the binary data $h$ that it outputs as an integer. The integer value of this digest is $\sum_{i=0}^n h_i 2^i$, in other words the digest is a base 2 representation of the integer.
In your case, since python has a notion of types, we need to take the binary string and convert it to an integer type. The builtin int function can do this for us:
int(x=0) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
The hexdigest call will return a hex string which is base 16, so you would want to do something like int_value = int(hash_value, 16).

fixed field width for float python [duplicate]

I read a lot of discussion about this on SE, but still can't find the right one.
I want to plot some numbers, of various lengths, with the same number of digits.
For example I have: 12.345678, 1.2345678. Now, since I have to plot them with their error, I want that each one has a different format, in order that they are significant.
So, I want to plot them with a variable number of decimals. In my case, it makes no sense to plot 23.45678+/-1.23456 but better is 23.4+/-1.2. On the other hand, I need that 1.234567+/-0.034567 becomes 1.23+/-0.03.
So, let's say, I want to plot all the numbers with a fixed width, could be 3 digits in total plus the comma. I should use something like '%1.1f' %num, but I can't find the right way. How can I do that?
I recommend defining a class that interprets a string formatter to give what you want.
Inside that class, you determine the length of the integer portion of your float and use that to define the appropriate string format.
In a nutshell, the class creates a formatter like '{:4.1f}' if your input is 12.345 (because you have two digits before the decimal separator) and {:4.2f} if your input it 1.2345 (because you have only one digit before the decimal separator). The total number of digits (4in this example) is provided as an input.
The new formatter is: {:nQ} where n is the total number of digits (so in the above example, you'd specify {:4Q}to get the output you want.
Here's the code:
import math
class IntegerBasedFloat(float):
def __format__(self, spec):
value = float(self)
# apply the following only, if the specifier ends in Q
# otherwise, you maintain the original float format
if spec.endswith('Q'):
# split the provided float into the decimal
# and integer portion (for this math is required):
DEC, INT = math.modf(value)
# determine the length of the integer portion:
LEN = len(str(abs(int(INT))))
# calculate the number of available decimals
# based on the overall length
# the -1 is required because the separator
# requires one digit
DECIMALS = int(spec[-2]) - LEN - 1
if DECIMALS < 0:
print 'Number too large for specified format'
else:
# create the corresponding float formatter
# that can be evaluated as usual:
spec = spec[-2] + '.' + str(DECIMALS) + 'f'
return format(value, spec)
DATA = [12.345, 2.3456, 345.6789]
print '{:4Q}'.format(IntegerBasedFloat(DATA[0]))
print '{:4Q}'.format(IntegerBasedFloat(DATA[1]))
print '{:4Q}'.format(IntegerBasedFloat(DATA[2]))
print 'This is a "custom" float: {:5Q} and a "regular" float: {:5.3f}'.format(IntegerBasedFloat(12.3456),12.3456)
The output should be:
12.3
2.35
346
This is a "custom" float: 12.35 and a "regular" float: 12.346
This answer is inspired by:
- splitting a number into the integer and decimal parts in python
- Add custom conversion types for string formatting

Fixed digits number in floats

I read a lot of discussion about this on SE, but still can't find the right one.
I want to plot some numbers, of various lengths, with the same number of digits.
For example I have: 12.345678, 1.2345678. Now, since I have to plot them with their error, I want that each one has a different format, in order that they are significant.
So, I want to plot them with a variable number of decimals. In my case, it makes no sense to plot 23.45678+/-1.23456 but better is 23.4+/-1.2. On the other hand, I need that 1.234567+/-0.034567 becomes 1.23+/-0.03.
So, let's say, I want to plot all the numbers with a fixed width, could be 3 digits in total plus the comma. I should use something like '%1.1f' %num, but I can't find the right way. How can I do that?
I recommend defining a class that interprets a string formatter to give what you want.
Inside that class, you determine the length of the integer portion of your float and use that to define the appropriate string format.
In a nutshell, the class creates a formatter like '{:4.1f}' if your input is 12.345 (because you have two digits before the decimal separator) and {:4.2f} if your input it 1.2345 (because you have only one digit before the decimal separator). The total number of digits (4in this example) is provided as an input.
The new formatter is: {:nQ} where n is the total number of digits (so in the above example, you'd specify {:4Q}to get the output you want.
Here's the code:
import math
class IntegerBasedFloat(float):
def __format__(self, spec):
value = float(self)
# apply the following only, if the specifier ends in Q
# otherwise, you maintain the original float format
if spec.endswith('Q'):
# split the provided float into the decimal
# and integer portion (for this math is required):
DEC, INT = math.modf(value)
# determine the length of the integer portion:
LEN = len(str(abs(int(INT))))
# calculate the number of available decimals
# based on the overall length
# the -1 is required because the separator
# requires one digit
DECIMALS = int(spec[-2]) - LEN - 1
if DECIMALS < 0:
print 'Number too large for specified format'
else:
# create the corresponding float formatter
# that can be evaluated as usual:
spec = spec[-2] + '.' + str(DECIMALS) + 'f'
return format(value, spec)
DATA = [12.345, 2.3456, 345.6789]
print '{:4Q}'.format(IntegerBasedFloat(DATA[0]))
print '{:4Q}'.format(IntegerBasedFloat(DATA[1]))
print '{:4Q}'.format(IntegerBasedFloat(DATA[2]))
print 'This is a "custom" float: {:5Q} and a "regular" float: {:5.3f}'.format(IntegerBasedFloat(12.3456),12.3456)
The output should be:
12.3
2.35
346
This is a "custom" float: 12.35 and a "regular" float: 12.346
This answer is inspired by:
- splitting a number into the integer and decimal parts in python
- Add custom conversion types for string formatting

Categories