I am looking at the SNMPBEECodec which can be seen at this location
In particular I am looking at the function encodeLength()
A snippet I am interested in
int numBytes = 0;
int temp = length;
while (temp > 0)
{
++numBytes;
temp = (int)Math.floor(temp / 256);
}
(from the Drexel SNMP library).
I would like to know why Math.floor()
is used instead of just a simple integer division like temp/256
. It seems the simple integer division would give the same result. Or is there a technical difference?
floor(x/y) , is equal to the integer division.
Floor division is a normal division operation except that it returns the largest possible integer. This integer is either less than or equal to the normal division result. Floor function is mathematically denoted by this ⌊ ⌋ symbol.
The floor division operator ( // ) is primarily used when you require an integer or need to return the smallest integer less than or equal to the input. If the operands are both integers, then the output will an integer.
floor() The Math. floor() function always rounds down and returns the largest integer less than or equal to a given number.
To answer the technical part of your question:
Using math.floor()
is superfluous: temp / 256
is an integer (by Java's rules for integer arithmetic), and using Math.floor()
on an integer is pointless. You could simply use temp / 256
.
Why the author did this is impossible to answer without reading their mind. The author might simply have been confused about the behaviour of division in Java, and decided to "play it safe" - but that is just speculation.
Well, unfortunately the author can no longer read his mind either - it's been about 12 years since I wrote this, so I forget the reason I didn't just use integer division. Some thoughts: I use integer division elsewhere assuming the usual behavior, so it wouldn't likely have been basic confusion on the rules for integer division in Java; it's possible (though unlikely) that I was at some point using a non-integral data type for the argument, and didn't get rid of the superfluous floor() when I changed; or perhaps (more likely) I was at some point attempting to round up rather than down while developing the algorithm, using ceil() as a cheap (= fewer characters) way to do this, and just reflexively switched to floor() when I changed.
So unfortunately the real reason is lost in the mists of time... but I agree, the floor() is superfluous. I should really post the code on Github or the like so folks can improve and evolve it. \ Jon
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With