Praktische Codebeispiele
Echtwelt-Szenarien der Umwandlung von Long in Hexadezimal
1. Generierung eindeutiger Identifikatoren
public class UniqueIdentifierGenerator {
public static String generateHexId(long seed) {
return Long.toHexString(System.currentTimeMillis() + seed);
}
public static void main(String[] args) {
String uniqueId = generateHexId(1000L);
System.out.println("Unique Hex ID: " + uniqueId);
}
}
2. Bitweise Operationen und hexadezimale Darstellung
public class BitwiseHexExample {
public static void main(String[] args) {
long value = 0xFFFF; // Hexadecimal literal
String hexRepresentation = Long.toHexString(value);
System.out.println("Hex Value: " + hexRepresentation);
// Bitwise manipulation
long shiftedValue = value << 8;
System.out.println("Shifted Hex: " + Long.toHexString(shiftedValue));
}
}
Visualisierung des Umwandlungsflusses
graph TD
A[Long Value] --> B[Conversion Method]
B --> C[Hex Representation]
C --> D[Further Processing]
3. Farbdarstellung in Grafiken
public class ColorHexConverter {
public static String rgbToHex(int red, int green, int blue) {
long colorValue = (red << 16) | (green << 8) | blue;
return String.format("%06X", colorValue);
}
public static void main(String[] args) {
String primaryRed = rgbToHex(255, 0, 0);
System.out.println("Red Color Hex: " + primaryRed);
}
}
Vergleich der Umwandlungsmethoden
Szenario |
Empfohlene Methode |
Leistung |
Einfache Umwandlung |
Long.toHexString() |
Hoch |
Formatierte Ausgabe |
String.format() |
Mittel |
Komplexe Manipulation |
Manuelle Umwandlung |
Variabel |
4. Simulation eines kryptografischen Hashes
public class HashSimulation {
public static String generateHexHash(long input) {
long hash = input * 31 + System.currentTimeMillis();
return Long.toHexString(Math.abs(hash));
}
public static void main(String[] args) {
String simulatedHash = generateHexHash(12345L);
System.out.println("Simulated Hash: " + simulatedHash);
}
}
Ausführung im Ubuntu-Terminal
## Compile Java files
javac UniqueIdentifierGenerator.java
javac BitwiseHexExample.java
javac ColorHexConverter.java
javac HashSimulation.java
## Run examples
java UniqueIdentifierGenerator
java BitwiseHexExample
java ColorHexConverter
java HashSimulation
Bei LabEx konzentrieren wir uns darauf, praktische, realweltnahe Codetechniken bereitzustellen, die die Vielseitigkeit der Umwandlung von Long in Hexadezimal in der Java-Programmierung demonstrieren.