0

In my project, ID is designed as snowflakeid. The front end passes a string to me, and the database storage is bigint. This means that before I store it, it needs to be converted to uint. Please tell me what to do? demo data :

m := "156343853366906880"

my code:
u, _ := strconv.ParseUint(m, 0, 19)

The expected results are accurate and will not lose accuracy

2
  • 4
    You haven't asked a question. Commented Nov 14, 2020 at 7:33
  • Sorry it's my problem, my english is not good Commented Nov 14, 2020 at 8:12

2 Answers 2

2

Third parameter of strconv.parseUint() is bitSize. 19 bits are not sufficient to represents the number 156343853366906880. So the method returns an error. (which you are ignoring by assigning it to _)

m := "156343853366906880"
_, err := strconv.ParseUint(m, 0, 19)
fmt.Println(err)
//strconv.ParseUint: parsing "156343853366906880": value out of range 524287

2^19 - 1 = 524287 is the biggest unsigned number that can be represented with 19 bits.

Pass 64 as bitSize :

m := "156343853366906880"
u, err := strconv.ParseUint(m, 0, 64)
if err == nil {
    fmt.Print(u)
    //156343853366906880
}

If your number is going to greater than uint64 use big.Int :

string to big Int in Go?

Sign up to request clarification or add additional context in comments.

Comments

0

SnowflakeID is a time based 64-bit unique id. Since you need to convert string to a 64-bit number, strconv.ParseUint() is quite good. See, the reference at ParseUint.

In your code, you used 19 as bit size. Do not mix it with the number of digit(s) in the integer (unsigned) represented by the string from frontend.

For convert a 64-bit SnowflakeID (string) into a 64-bit unsigned integer, use 64 as bitSize arg.

U, err := strvonv.ParseUint(s, 0, 64)
if err != nil {
    // handle error... 
}

Also do not try to ignore error, when it really matters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.