How to convert int (4 bytes) to hex ("XX XX XX XX
") without cycles?
for example:
i=13 hex="00 00 00 0D"
i.ToString("X")
returns "D"
, but I need a 4-bytes hex value.
To convert an integer i to a string with leading zeros so that it consists of 5 characters, use the format string f'{i:05d}' . The d flag in this expression defines that the result is a decimal value. The str(i). zfill(5) accomplishes the same string conversion of an integer with leading zeros.
You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string.
Python hex() Function The hex() function converts the specified number into a hexadecimal value. The returned string always starts with the prefix 0x .
You can specify the minimum number of digits by appending the number of hex digits you want to the X
format string. Since two hex digits correspond to one byte, your example with 4 bytes needs 8 hex digits. i.e. use i.ToString("X8")
.
If you want lower case letters, use x
instead of X
. For example 13.ToString("x8")
maps to 0000000d
.
try this:
int innum = 123; string Hex = innum .ToString("X"); // gives you hex "7B" string Hex = innum .ToString("X8"); // gives you hex 8 digit "0000007B"
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