Tuesday, July 23, 2024
HomeGolangLearn how to left shift int32 with unfavorable quantity? Go - Code...

Learn how to left shift int32 with unfavorable quantity? Go[v1.21] – Code Overview


I wish to replicate following C code in GoLang

uint32_t xx = 0x1FA19141;
uint32_t n = 1759730200;
uint32_t temp1 = xx << (32 - n);

My implementation is as follows:

var n int = 1759730200
temp := int32(32 - n)
temp1 := int32(xx << temp)

Nonetheless, GoLang doesn’t appear to permit unfavorable shift,

I get runtime error as panic: runtime error: unfavorable shift quantity

In accordance with supply file go/expressions.c, go doesn’t appear to permit this operation for some motive

if (mpz_sgn(val) < 0)
{
  this->report_error(_("unfavorable shift rely"));
....
}

How can I power shift left by unfavorable quantity? Can anyone please assist me with this subject?

whats about with proper shift if shift quantity is unfavorable
for instance :

if temp > 0 {
 temp1  := int32(xx << temp)
} else {
 temp1 := int32(xx >> int32(math.Abs(temp)))
}

This doesn’t work as math.Abs count on float.

Even with following:

if temp > 0 {
 temp1  := int32(xx << temp)
} else {
 temp1 := int32(xx >> int32(math.Abs(float64(temp))))
}

This can end in temp1 being 0 for the reason that shift worth is simply too lengthy.

I’m not positive why this works flawlessly with the C and clang+11 compilers.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments