Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

Java - convert long to hex String

0 contributions
14 points

Short solution:

long number = 10;
String hexString = Long.toHexString(number);
System.out.println(hexString); // a

Other simple examples:

System.out.println( Long.toHexString(1)  ); // 1
System.out.println( Long.toHexString(9)  ); // 9
System.out.println( Long.toHexString(10) ); // a
System.out.println( Long.toHexString(15) ); // f
System.out.println( Long.toHexString(16) ); // 10
System.out.println( Long.toHexString(17) ); // 11
System.out.println( Long.toHexString(30) ); // 1e
System.out.println( Long.toHexString(31) ); // 1f
System.out.println( Long.toHexString(32) ); // 20
System.out.println( Long.toHexString(33) ); // 21

1. Print long and hex values from 0 to 20

public class Example1 {

    public static void main(String[] args) {

        for (long number = 0; number <= 20; number++) {
            String hex = Long.toHexString(number);

            System.out.println("dec: " + number + ", hex: " + hex);
        }
    }
}

Output:

dec: 0, hex: 0
dec: 1, hex: 1
dec: 2, hex: 2
dec: 3, hex: 3
dec: 4, hex: 4
dec: 5, hex: 5
dec: 6, hex: 6
dec: 7, hex: 7
dec: 8, hex: 8
dec: 9, hex: 9
dec: 10, hex: a
dec: 11, hex: b
dec: 12, hex: c
dec: 13, hex: d
dec: 14, hex: e
dec: 15, hex: f
dec: 16, hex: 10
dec: 17, hex: 11
dec: 18, hex: 12
dec: 19, hex: 13
dec: 20, hex: 14

2. Convert hex String to long

public class Example2 {

    public static void main(String[] args) {

        String hexString = "a";
        long number = Long.valueOf(hexString, 16);

        System.out.println(number); // 10
    }
}

Output:

10

References

  1. Decimal - wikipedia
  2. Hexadecimal - wikipedia
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more