Home > Backend Development > Golang > Why does printing -1 as hexadecimal in Go and C produce different results?

Why does printing -1 as hexadecimal in Go and C produce different results?

Mary-Kate Olsen
Release: 2024-11-16 00:58:03
Original
240 people have browsed it

Why does printing -1 as hexadecimal in Go and C produce different results?

Understanding Hexadecimal Printing Differences between Go and C: The Case of -1

In Go, the %x format for printing integers represents the value in hexadecimal notation. This is distinct from C's %x, which prints the memory representation of a signed integer. This difference leads to unexpected results when printing the negative integer -1.

In Go:

var x uint64 = 1 << 64 - 1
fmt.Printf("%x\n", x)
Copy after login

Output:

ffffffffffffffffffff
Copy after login

Here, %x correctly prints the hexadecimal representation of the unsigned value 1<<64 - 1.

In C:

#include <stdio.h>
int main() {
  uint64_t x = 1LL << 64 - 1;
  printf("%x\n", (long long)x);
}
Copy after login

Output:

-1
Copy after login

In C, %x prints the signed integer value -1, seemingly resulting in a negative hexadecimal number with a leading '-'. However, this is not the case; the '-' sign indicates that the integer is negative, and the hexadecimal value ffff...ff is the 2's complement representation of -1.

Go enforces strict typing, requiring explicit type conversions to treat signed integers as unsigned. To print -1 as an unsigned value in Go:

i := -1 // type int
fmt.Printf("%x", uint(i))
Copy after login

Output:

ffffffff
Copy after login

This approach converts the signed integer -1 to its unsigned counterpart, resulting in the correct hexadecimal representation.

The default behavior of Go to print negative integers as signed values allows for concise representation, but it can lead to unexpected results in hexadecimal contexts. Understanding these differences is crucial for effective code writing in Go.

The above is the detailed content of Why does printing -1 as hexadecimal in Go and C produce different results?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template