如何将Unix时间戳转换为十六进制?

huangapple go评论77阅读模式
英文:

How to convert unix timestap to hexadecimal

问题

我有这段C代码,我想要将其翻译成Go语言:

package main

import (
	"fmt"
	"time"
)

func main() {
	started := time.Now()
	ms := started.UnixNano() / 1000000
	fmt.Printf("Time: %011x\n", ms)
}

然而,我不知道如何将这个数字转换为十六进制(与我所拥有的C代码的输出相似)。我找到了如何解码十六进制时间戳的方法,可以参考这个问题/答案。有人可以指点我吗?

英文:

I have this snippet of C code that I'm trying to translate to Go:

#include <sys/time.h>
#include <sys/types.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>



int main()
{
    struct timeval started;
    int64_t ms;
    
    gettimeofday(&started, NULL);
    ms = (int64_t) started.tv_sec * 1000 + started.tv_usec / 1000;
    printf("Time: %011"PRIx64"\n", ms);

    return 0;
}

I've found how to convert unix time to millieseconds by using the below snippet:

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Printf("Unix Time in ms: %d \n", time.Now().UnixNano() / 1000000)
}

However I'm having a hard time how to convert that number into hexadecimal (That somewhat resembles the output of the C code that I have.) I did find how to decode the hextime stamp using this questions / answer. Can anyone point me in the right direction?

答案1

得分: 1

我已经为您翻译了代码,请查看以下内容:

这应该是正确的解决方案:

package main

import (
    "fmt"
    "time"
)

func main() {
    unix_time_ms := 1589664726314
    fmt.Printf("Hex Unixtime in MS: %x ,should equal 1721f66bd2a\n", unix_time_ms)
}

在C语言中,应该匹配以下代码:

#include <stdio.h>
#include <inttypes.h>

int main()
{
    int64_t unix_time_ms;
    unix_time_ms = 1589664726314;
    
    printf("Hex Unixtime in MS: %011"PRIx64"\n", unix_time_ms);

    return 0;
}

请注意,我只翻译了代码部分,其他内容不包括在内。

英文:

Think this should be the right solution:

package main

import (
    &quot;fmt&quot;
    &quot;time&quot;
)

func main() {
    unix_time_ms := 1589664726314
    fmt.Printf(&quot;Hex Unixtime in MS: %x ,should equal 1721f66bd2a\n&quot;, unix_time_ms)
}

In C it should match this:

int main()
{
    int64_t unix_time_ms;
    unix_time_ms = 1589664726314;
    
    printf(&quot;Hex Unixtime in MS: %011&quot;PRIx64&quot;\n&quot;, unix_time_ms);

    return 0;
}

答案2

得分: -1

你可以在Go语言中使用'%XF'来打印十六进制数。就像下面的例子一样:

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Printf("Unix Time in ms: %XF \n", time.Now().UnixNano() / 1000000)
}

Playground链接在这里

英文:

You can use &#39;%XF&#39; to print hexadecimal in goalng. Like the following

package main

import (
    &quot;fmt&quot;
    &quot;time&quot;
)

func main() {
    fmt.Printf(&quot;Unix Time in ms: %XF \n&quot;, time.Now().UnixNano() / 1000000)
}

Playground link here.

huangapple
  • 本文由 发表于 2020年5月17日 03:00:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/61842119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定