How do I convert the integer -2 to its hex 0xfe???
I tried hex() but it gives me -0x2

Dani AI

Generated

Short answer: Python prints hex(-2) as -0x2 because integers are signed and unbounded. To see the byte-level (two's‑complement) view you must pick a bit width and reinterpret the value as an unsigned integer. already pointed to the unsigned-byte view; correctly reminded that the hex representation depends on the size you choose (byte, word, dword, qword).

A small, general helper that returns the unsigned two's‑complement hex string for any bit width:

def to_unsigned_hex(value, bits=8):
    mask = (1 << bits) - 1
    unsigned = value & mask
    width = (bits + 3) // 4    # number of hex digits
    return f"0x{unsigned:0{width}x}"

Alternative: if you need the actual packed bytes (so endianness and exact bytes matter), use the struct/binascii route to get the raw byte sequence and its hex. That is useful when writing to files or talking to hardware/protocols — pick the signed/unsigned format and byte order explicitly.

Troubleshooting notes: be explicit about the bit width you expect (8, 16, 32, 64); masking with & is fast and portable; when packing use the correct struct format character and endianness; do not rely on hex() alone if you want an unsigned, fixed-width representation. See the Python docs for struct and binascii for packing and hex-encoding details: struct — Interpret bytes as packed binary data and binascii — Convert between binary and ASCII.

Recommended Answers

All 2 Replies

0xfe is not the hex of -2, it is the hex of 256 - 2. You can use

>>> hex(-2 % 256)
'0xfe'
>>> hex(256 - 2)
'0xfe'

0xfe is not the hex of -2, it is the hex of 256 - 2. You can use

>>> hex(-2 % 256)
'0xfe'
>>> hex(256 - 2)
'0xfe'

Actually, it is for byte.

If I can remember correctly, Windows, -2 is:
Qword (long) = 0xFFFFFFFFFFFFFFFE
Dword (int) = 0xFFFFFFFE
Word (short) = 0xFFFE
Byte = 0xFE

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.