英文:
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 (
"fmt"
"time"
)
func main() {
unix_time_ms := 1589664726314
fmt.Printf("Hex Unixtime in MS: %x ,should equal 1721f66bd2a\n", unix_time_ms)
}
In C it should match this:
int main()
{
int64_t unix_time_ms;
unix_time_ms = 1589664726314;
printf("Hex Unixtime in MS: %011"PRIx64"\n", 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 '%XF'
to print hexadecimal in goalng. Like the following
package main
import (
"fmt"
"time"
)
func main() {
fmt.Printf("Unix Time in ms: %XF \n", time.Now().UnixNano() / 1000000)
}
Playground link here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论