Home >Backend Development >Golang >How to Display UTF-8 Strings Correctly in Windows Consoles?

How to Display UTF-8 Strings Correctly in Windows Consoles?

DDD
DDDOriginal
2024-11-02 21:55:30632browse

How to Display UTF-8 Strings Correctly in Windows Consoles?

Encoding UTF-8 Strings for Display in Windows Consoles

When executing a Go executable in a Windows console, strings with special characters may appear mangled due to the console's default IBM850 encoding. Here's how to ensure that strings are correctly encoded and displayed:

Solution:

Utilize the WriteConsoleW function from the kernel32.dll library to write wide character (UTF-16) strings directly to the console, bypassing the default encoding.

Implementation:

<code class="go">import (
    "syscall"
    "unicode/utf16"
    "unsafe"
)

// Declare the WriteConsoleW function
var procWriteConsoleW = syscall.NewLazyDLL("kernel32.dll").NewProc("WriteConsoleW")

// Define a function to print a UTF-8 string to the console
func consolePrintString(strUtf8 string) {
    // Convert the UTF-8 string to UTF-16
    strUtf16 := utf16.Encode([]rune(strUtf8))

    // Write the UTF-16 string to the console
    syscall.Syscall6(procWriteConsoleW.Addr(), 5,
        uintptr(syscall.Stdout),
        uintptr(unsafe.Pointer(&strUtf16[0])),
        uintptr(len(strUtf16)),
        uintptr(unsafe.Pointer(nil)),
        uintptr(0),
        0)
}</code>

Example:

<code class="go">package main

import "fmt"

func main() {
    consolePrintString("Hello ☺\n")
    consolePrintString("éèïöîôùòèìë\n")
}</code>

This approach bypasses the console's default encoding, ensuring that strings with special characters are correctly displayed. Please note that it is Windows-specific and involves the use of undocumented methods.

The above is the detailed content of How to Display UTF-8 Strings Correctly in Windows Consoles?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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