Skip to content

Instantly share code, notes, and snippets.

@babon
Created November 21, 2022 11:13
Show Gist options
  • Save babon/7383ce8ac4c7bb6d14243905284b29e8 to your computer and use it in GitHub Desktop.
Save babon/7383ce8ac4c7bb6d14243905284b29e8 to your computer and use it in GitHub Desktop.
void p(string s, uint n)
{
string ns = Convert.ToString(n, 2).PadLeft(32, '0');
var list = Enumerable.Range(0, ns.Length / 8).Select(i => ns.Substring(i * 8, 8));
var nsf = string.Join("_", list);
print(s + " ; " + nsf);
}
p("(1 << (32-7))", (1 << (32 - 7)));
p("((1 << (32-7)) - 1)", ((1 << (32 - 7)) - 1));
p("((1 << (32 - 7)) - 1) >> (32 - 7) - 1 << (32 - 7) - 1", ((1 << (32 - 7)) - 1) >> (32 - 7) - 1 << (32 - 7) - 1);
p("~(~0 << 7) << 1", ~(~0 << 7) << 1);
p("~(~0 << 4) << 32 - 7 - 4", ~(~0 << 4) << 32 - 7 - 4);
uint maskOfOnes(int startLeft, int amountLeft)
{
return ~(~0u << amountLeft) << 32 - startLeft - amountLeft;
}
//will use only amountLeft of rightmost bits from val
uint setbits(uint _, int startLeft, int amountLeft, uint val)
{
val = val << 32 - amountLeft >> startLeft;
uint mask = maskOfOnes(startLeft, amountLeft);
return (_ & ~mask) | (val & mask);
}
p("", setbits(2863311530, 24, 4, 9));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment