Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to hex with leading zeros

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.

like image 923
user2264990 Avatar asked Apr 10 '13 07:04

user2264990


People also ask

How do you convert integers to string with leading zeros?

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.

How can I add zero in front of a number in C#?

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.

What is hex int in Python?

Python hex() Function The hex() function converts the specified number into a hexadecimal value. The returned string always starts with the prefix 0x .


2 Answers

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.

like image 77
CodesInChaos Avatar answered Oct 06 '22 07:10

CodesInChaos


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" 
like image 26
KF2 Avatar answered Oct 06 '22 07:10

KF2