How to left shift int32 with negative number? Go[v1.21]

I would like 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)

However, GoLang does not seem to allow negative shift,

I am getting runtime error as panic: runtime error: negative shift amount

According to source file go/expressions.c, go doesn’t seem to allow this operation for some reason

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

How can I force shift left by negative number? Can somebody please help me with this issue?

whats about with right shift if shift number is negative
for example :

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

This doesn’t work as math.Abs expect float.

Even with following:

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

This will result in temp1 being 0 since the shift value is too long.

I am not sure why this works flawlessly with the C and clang+11 compilers.

confused as well with me

  • This means even if the most significant bit (the sign bit) gets shifted out, it’s still considered negative.