Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. package ir.h76.javaproblems.algorithms;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class DecimalToHex {
  6. /**
  7. * Steps of converting decimal to Hexadecimal
  8. * 1- Divide the decimal number by 16. Treat the division as an integer division
  9. * 2- Write down the remainder (in hexadecimal)
  10. * 3- Divide the result again by 16. Treat the division as an integer division
  11. * 4- Repeat step 2 and 3 until result is 0
  12. * 5- The hex value is the digit sequence of the remainders from the last to first
  13. *
  14. * @param int
  15. * @return String
  16. */
  17. public static String convert(int dec) {
  18. String digits = "0123456789ABCDEF";
  19. if (dec <= 0) return "0";
  20. int base = 16;
  21. String hex = "";
  22.  
  23. while (dec > 0) {
  24. int digit = dec % base;
  25. hex = digits.charAt(digit) + hex;
  26. dec = dec / base;
  27. }
  28.  
  29. return hex;
  30. }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement