Popcount, ARGV, and threads count

I’ve done searching for these but haven’t found the definitive answers.
I need the Go translation of these Crystal snippets.

A. Go popcount or equivalent to Crystal.

seg[0..(kn - 1) >> s].each { |m| cnt += (1 << s) - m.popcount }

Go gives errors. Does it have popcount?

for m = range seg[0..(kn - 1) >> s] { cnt += (1 << s) - popcount(m) 

B. Print number of cpu threads

puts "threads = #{System.cpu_count}"

Go?

fmt.Printf("threads = %d\n", ???)

C. Read one or two 64-bit unsigned number from command line like so in Crystal.

end_num   = {ARGV[0].to_u64, 3}.max 
start_num = ARGV.size > 1 ? {ARGV[1].to_u64, 3}.max : 3
start_num, end_num = end_num, start_num if start_num > end_num

Go? - how to get|use ARGV and convert vals to uint|64, take max of 3 or it.

end_num := math.Max(unit64(ARGV[0]), 3)
if len(ARGV) > 1 {start_num := math.Max(unit64(ARGV[1]), 3}} else {start_num := 3}
if start_num > end_num { start_num, end_num = end_num, start_num }
  1. Took me a while to figure out what a “popcount” is, after I figured, answer was obvious: `math/bits.OnesCount*().
  2. If I understand correctly you want runtime.NumCPU()
  3. To read args either use flag package or directly access os.Args + strconv package.

Take A Tour of Go.

A. math/bits

B. runtime

C. strconv, os, and flag

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.