I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings.
How can I do this?
Converting one datatype into another is known as type casting or, type-conversion. For example, if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the values from one type to another explicitly using the cast operator as follows − (type_name) expression.
Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double.
Methods of Type Casting Type Casting is categorized into two types: Implicit Type Casting – conversion of data types is done automatically by Python. Explicit Type Casting – conversion of data types is done by the user.
You can convert a string to a 32-bit signed integer with the int
function:
str = "1234" i = int(str) // i is a 32-bit integer
If the string does not represent an integer, you'll get a ValueError
exception. Note, however, that if the string does represent an integer, but that integer does not fit into a 32-bit signed int, then you'll actually get an object of type long
instead.
You can then convert it to other widths and signednesses with some simple math:
s8 = (i + 2**7) % 2**8 - 2**7 // convert to signed 8-bit u8 = i % 2**8 // convert to unsigned 8-bit s16 = (i + 2**15) % 2**16 - 2**15 // convert to signed 16-bit u16 = i % 2**16 // convert to unsigned 16-bit s32 = (i + 2**31) % 2**32 - 2**31 // convert to signed 32-bit u32 = i % 2**32 // convert to unsigned 32-bit s64 = (i + 2**63) % 2**64 - 2**63 // convert to signed 64-bit u64 = i % 2**64 // convert to unsigned 64-bit
You can convert strings to floating point with the float
function:
f = float("3.14159")
Python floats are what other languages refer to as double
, i.e. they are 64-bits. There are no 32-bit floats in Python.
The following types -- for the most part -- don't exist in Python in the first place. In Python, strings are converted to ints, longs or floats, because that's all there is.
You're asking for conversions that aren't relevant to Python in the first place. Here's the list of types you asked for and their Python equivalent.
unsigned and signed int 64 bits, long
double, float
I don't know what the following are, so I don't know a Python equivalent.
You already have all the conversions that matter: int()
, long()
and float()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With