Skip to main content

How to Convert Data Types to Hexadecimal in Kotlin?

Photo by Ted Balmer on Unsplash

Hexadecimal is a base-16 number system commonly used in programming for its concise representation of binary values. Converting various data types to hexadecimal format can be particularly useful in scenarios like memory addressing, color representation, and data serialization. In this article, we will explore how to convert different data types to hexadecimal in Kotlin, complete with practical examples.

Understanding Hexadecimal

Hexadecimal (often abbreviated as hex) uses sixteen symbols: 0-9 represent values zero to nine, and A-F represent values ten to fifteen. This representation allows for more compact notation compared to binary (base-2) or decimal (base-10) systems. For example, the decimal number 255 is represented as FF in hexadecimal.

Comparison of Number Systems:

Decimal Binary Hexadecimal
10 1010 A
15 1111 F
255 11111111 FF

Setting Up Your Kotlin Environment

To try the code with Kotlin, you can use the Kotlin Playground: 

Converting Data Types to Hexadecimal

Converting Integer to Hexadecimal

The first function we will create is integerToHex, which converts an integer to its hexadecimal representation.

fun integerToHex(input: Int): String {
    var result = input.toString(16).toUpperCase()
    
    if (result.length % 2 != 0) {
        result = "0$result"
    }

    return result
}

Converting ASCII Strings to Hexadecimal

Next, we’ll create a function to convert ASCII strings to hexadecimal using asciiToHex.

fun asciiToHex(input: String): String {
    return input.map { char -> "${char.code.toString(16).uppercase()}" }
        .joinToString("")
}

Converting Dates to Hexadecimal

For converting dates, we will implement dateToHex, which converts an ISO 8601 date string to its hexadecimal representation.

import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

fun dateToHex(input: String): String {
    val dateTime = OffsetDateTime.parse(input, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
    return dateTime.toEpochSecond().toString(16).toUpperCase()
}

Converting Durations to Hexadecimal

Lastly, we’ll implement durationToHex, which converts ISO 8601 duration strings to hexadecimal.

import java.time.Duration

fun durationToHex(input: String): String {
    val duration = Duration.parse(input)
    return duration.seconds.toString(16).toUpperCase().padStart(4, '0')
}

Practical Examples

Here’s a complete main function demonstrating the use of all the conversion functions:

fun main() {
    println("Hex of 255: ${integerToHex(255)}")
    println("Hex of 'Hello': ${asciiToHex("Hello")}")
    println("Hex of date: ${dateToHex("2024-09-30T12:34:56Z")}")
    println("Hex of duration: ${durationToHex("PT1H30M")}")
}

Common Use Cases

Converting data types to hexadecimal is commonly used in various programming scenarios, including:

  • Memory Addresses: Hexadecimal representation is often used to denote memory addresses in programming languages.
  • Color Codes: In web development, colors are typically represented in hex format (e.g., #FFFFFF for white).
  • Data Serialization: Hexadecimal is used in data serialization formats to represent binary data in a human-readable form.


In this article, we covered the process of converting various data types to hexadecimal in Kotlin. We explored functions for converting integers, ASCII strings, ISO 8601 dates, and durations. By understanding these conversions, you can enhance your programming skills and handle hexadecimal representations more effectively.

I invite you to try out these functions in your own Kotlin projects! Share your experiences or ask any questions in the comments below. 

Don't forget to subscribe to my blog so you never miss out on my latest guides and content!

Comments

Popular posts from this blog

Selenium for Beginners: What, Where, When, and Why to Use It in Automated Testing

In today’s software development landscape, automated testing has become essential for delivering robust applications efficiently. Among various automated testing tools,   Selenium   stands out as one of the most widely used and beginner-friendly options. As you embark on your journey into automated testing, it’s crucial to understand the   what, where, when, and why   of using Selenium. In this guide we will run through these essentials and help you decide if Selenium is the right tool for you. What is Selenium? Selenium  is an open-source framework used primarily for automating web browsers. It enables developers and testers to write scripts that interact with websites, simulating actions like clicking buttons, filling out forms, and navigating pages, which allows for comprehensive automated testing. Selenium supports multiple programming languages, including Python, Java, C#, and JavaScript, making it flexible for teams with different coding preferences. Key Components of Selenium: S

ORM vs Non-ORM: Choosing the Right Approach for Your Database Queries

As developers, we often face decisions that affect how we interact with databases in our applications. One critical choice is whether to use an ORM (Object-Relational Mapping) tool or stick with traditional non-ORM methods like writing raw SQL queries or using query builders. Each approach has its advantages and disadvantages, and the decision depends on several factors, such as the complexity of the queries, project requirements, and the design of the database itself. In this guide, we’ll explore the key differences between ORM and non-ORM approaches, discuss when to use each, and highlight the pros and cons to help you make the right decision for your next project. What is an ORM? An ORM is a tool or library that allows developers to interact with a relational database using an object-oriented paradigm. It maps database tables to classes, rows to objects, and columns to attributes, allowing developers to work with data using their programming language’s syntax rather than writing SQL

The Weight of Responsibility: A Developer’s Journey to Balance Passion and Reality

For the past several years, Eddie has been on a steady climb in his career as a developer, but recently, he found himself at a crossroads — caught between the weight of his responsibilities and the desire to pursue his true passions. His journey began with a three-month internship as a web developer, which led to nearly four years in an application developer role. After that, he spent almost a year as a systems associate, managing tasks across systems analysis, quality assurance, and business analysis. Eventually, he returned to full-time software development for another two years before transitioning into more complex roles. For over a year, he worked as a multi-role software developer and database administrator before stepping into his current position as a senior software developer, database administrator, and cloud administrator — occasionally handling security tasks as well. Now, with over 8 years of professional experience, he also leads a small team of developers, which has been

Avoiding Confusion in API Design: The Importance of Clear Responses

In today’s fast-paced software development landscape, APIs play a crucial role in connecting services and enabling functionality. However, poor design choices can lead to confusion and inefficiency for both developers and users. One such choice is the omission of a response body for successful requests, a practice I recently encountered in an enterprise API designed for bill payments. The Case of the No-Response API The API in question serves two main endpoints: one for inquiring about account validity and another for confirming payment. When successful, the API returned a  200 OK  status but no response body. This design choice led to significant confusion during our integration process. Even the internal team who developed the said API struggled to justify this approach, revealing a lack of clarity around the rationale behind it. Pros of This Design Choice While the intention behind this design may have been to streamline responses, several potential benefits can be identified: Reduc

The Hidden Costs of Overdesign and Bad Practices in API Systems

In software development, simplicity and clarity are often sacrificed in favor of overly complex solutions. While it can be tempting to add more features and intricate designs to ensure robustness, overdesign and poor practices can have significant consequences. They frustrate developers, lead to inefficiencies, increase costs, and put unnecessary strain on system resources.  A recent example involving a team that has faced challenges with complexity highlights the pitfalls of such an approach. Overdesign: The Problem of Too Much Complexity Overdesign occurs when systems are built with more complexity than necessary. This might manifest in bloated APIs, convoluted data flows, or excessive checks and processes that don’t add substantial value. The goal is often to anticipate future problems, but this approach typically results in cumbersome systems that are difficult to maintain and scale. In one case, a company found itself paying a hefty price just to host two API services and a portal