C
C#4w ago
mynarco

Get minimum bytes needed for a number in c#

I have this method in python that gives me the minimum bytes needed for a number
def get_time_byte_size(self, time):
return (time.bit_length() + 7) // 8
def get_time_byte_size(self, time):
return (time.bit_length() + 7) // 8
for a number like 122 it will return 1, and for like 257 it will return 2, so on and so forth
5 Replies
mynarco
mynarcoOP4w ago
i want to figure out a way to impliment it in python i was doing it like this
int GetBytesNeeded(ulong val) {
if(val > 255) return 1;
else if(val > 65535) return 2;
else if(val > 16777215) return 3;
else if(val > 4294967295) return 4;
return 0;
}
int GetBytesNeeded(ulong val) {
if(val > 255) return 1;
else if(val > 65535) return 2;
else if(val > 16777215) return 3;
else if(val > 4294967295) return 4;
return 0;
}
but i want to go as far as 8, and i dont want a super long if statement
Angius
Angius4w ago
Using a logarithm might be helpful
MODiX
MODiX4w ago
ero
REPL Result: Success
Console.WriteLine(ByteCount(255));
Console.WriteLine(ByteCount(256));

int ByteCount<T>(T v)
where T : IBinaryInteger<T>
{
return (v.GetShortestBitLength() + 7) / 8;
}
Console.WriteLine(ByteCount(255));
Console.WriteLine(ByteCount(256));

int ByteCount<T>(T v)
where T : IBinaryInteger<T>
{
return (v.GetShortestBitLength() + 7) / 8;
}
Console Output
1
2
1
2
Compile: 457.477ms | Execution: 29.926ms | React with ❌ to remove this embed.
ero
ero4w ago
Courtesy of #allow-unsafe-blocks
mynarco
mynarcoOP4w ago
oh wait thank you wtf. thats actually very useful
Want results from more Discord servers?
Add your server