• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

pad length of variable?

 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
I'm full of tinier men! And a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic