• Post Reply Bookmark Topic Watch Topic
  • New Topic

pad length of variable?  RSS feed

 
david lightman
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How would I pad the length something to be a multiple of 4?

for example I have a variable

int iLength;
and I get the length of a string myString and pass it to iLength, like

iLength = myString.length();

how to I then pad the iLenght to always be a mulitple of 4

thanks!
 
Mark Spritzler
ranger
Sheriff
Posts: 17309
11
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can always pad your string, but the calculation is to get the mod of the length, subtract it from four, and add the result to the int.

Mark
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or if you always want the minimum length, you can check to see if it's already divisible by 4 before adding...
 
david lightman
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Marc!

forgive me but to COMPLETELY understand, this code is basically saying

if(i%4 != 0) ---> if this number i is divided by 4 and the remainder is not zero,

then i += (4 - i%4); ---> divide i by 4 and and substract this number from 4
and place in back into the i.

so if i was 17

it would first say no there is a 1 left over..then it would subract the one from the 4 to give it three then add the three to the original 17 giving it a 20.

right?

I think I understand how it works, thanks
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, with the following addition in bold...

i += (4 - i%4); ---> divide i by 4 and substract this number from 4, then add the result to i and place back into the i.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!