Home > Backend Development > Golang > How to Print UTF-8 Strings Correctly in a Windows Console using Go?

How to Print UTF-8 Strings Correctly in a Windows Console using Go?

DDD
Release: 2024-11-01 01:23:28
Original
358 people have browsed it

How to Print UTF-8 Strings Correctly in a Windows Console using Go?

Ensuring Proper String Output in Windows Consoles with Go

Problem:
When using a Go executable to print UTF-8 strings in a Windows console, users may encounter mangled output due to the console's default IBM850 encoding. This can lead to special characters being displayed incorrectly.

Solution:
To guarantee accurate string output in a Windows console, use the following code:

<code class="go">// Alert: This method utilizes undocumented methods and does not handle stdout redirection or error checking.
// Use with caution.

package main

import (
    "syscall"
    "unicode/utf16"
    "unsafe"
)

var modkernel32 = syscall.NewLazyDLL("kernel32.dll")
var procWriteConsoleW = modkernel32.NewProc("WriteConsoleW")

func consolePrintString(strUtf8 string) {
    strUtf16 := utf16.Encode([]rune(strUtf8))
    if len(strUtf16) == 0 {
        return
    }

    var charsWritten *uint32
    syscall.Syscall6(procWriteConsoleW.Addr(), 5,
        uintptr(syscall.Stdout),
        uintptr(unsafe.Pointer(&strUtf16[0])),
        uintptr(len(strUtf16)),
        uintptr(unsafe.Pointer(charsWritten)),
        uintptr(0),
        0)
}

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

This code uses undocumented Windows API functions to write UTF-16 encoded strings directly to the console, bypassing the default encoding. This approach ensures that special characters are displayed correctly.

Usage:
In your Go program, you can directly call the consolePrintString function to print UTF-8 encoded strings that will be properly displayed in the Windows console.

The above is the detailed content of How to Print UTF-8 Strings Correctly in a Windows Console using Go?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template