-5

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?

tadman
  • 208,517
  • 23
  • 234
  • 262
InitEnabler
  • 63
  • 10
  • 2
    Have you read through the docs for the [fmt package](https://golang.org/pkg/fmt/)? – Marc May 16 '20 at 19:36
  • Read wikipedia page on [number](https://en.wikipedia.org/wiki/Number)s. Then the one on [time](https://en.wikipedia.org/wiki/Time). Then [time(7)](http://man7.org/linux/man-pages/man7/time.7.html) – Basile Starynkevitch May 16 '20 at 19:53
  • 1
    Lowercase hexadecimal representation with length 11 and zero padding is: `%011x`. – Marc May 16 '20 at 20:21

2 Answers2

1

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;
}
InitEnabler
  • 63
  • 10
-1

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.

Parvez M Robin
  • 154
  • 1
  • 3
  • 16
  • This answer is incorrect. `F` and `X` don't mix. You're also ignoring length, zero padding, and case. – Marc May 16 '20 at 20:20
  • @Marc I added a playground link and that clearly shows `F` and `X` mixes. – Parvez M Robin May 17 '20 at 12:58
  • They mix in the sense that it runs, but you end up with `123234F` where the trailing F is not part of the number, it's just the F you're printing. – Marc May 17 '20 at 13:11