Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

go - Writing powers of 10 as constants compactly

I'm reading the recently released The Go Programming Language, and it's been a joy so far (with Brian Kernighan being one of the authors, I wouldn't expect anything other than excellence anyway).

I've come across the following exercise on chapter 3:

Exercise 3.13 Write const declarations for KB, MB, up through YB as compactly as you can.

(NOTE: in this context, KB, MB, etc, denote powers of 1000)

This is preceded by a section where iota is introduced as a useful constants generator mechanism; in particular, the previous paragraph shows a nice and compact way to define the powers of 1024 as constants:

const (
    _ = 1 << (10 * iota)
    KiB
    MiB
    GiB
    TiB
    PiB
    EiB
    ZiB
    YiB
)

The authors further mention this regarding powers of 10:

The iota mechanism has its limits. For example, it's not possible to generate the more familiar powers of 1000 (KB, MB, and so son) because there is no exponentiation operator.

I'm struggling with this exercise because it looks like the expected solution is something a little more elaborate than simply spelling out the powers of 1000 by hand (especially since it appears after iota is introduced). I feel like there is some clever way to do this that uses iota in a subtle way combined with something else.

I thought about finding a systematic way to subtract the "excess" amount out of each of the powers of 1024 to get the powers of 1000, but it led me to nowhere. Then I looked at the binary representations to try and infer a general pattern where iota could be useful, but again, I got nothing.

I really can't see how one would generate powers of 1000 out of a single incrementing value (iota) without an exponentiation operator.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...