Java atoi itoa


You can, of course, use Integer.toHexString(int) and Integer.parseInt(String, int).

/**
 * Converts a single 7-bit ASCII value to a 4-bit unsigned integer. An
 * <code>IllegalArgumentException</code> will be thrown if given
 * <code>ascii</code> is in wrong range.
 *
 * @param ascii 7-bit ASCII value; digit (0x30 ~ 0x39),
 *        upper alpha (0x41 ~ 0x46), or lower alpha (0x61 ~ 0x66)
 * @return 4-bit unsigned integer (0x00 ~ 0x0F)
 */
static int atoi(final int ascii) {

    if (ascii < 0x30) { // ~ 0x2F('/')
        throw new IllegalArgumentException("wrong ascii: " + ascii);
    }

    if (ascii <= 0x39) { // 0x30('0') ~ 0x39('9')
        return ascii - 0x30; // 0x00, 0x01, ...
    }

    if (ascii <= 0x40) { // 0x3A(':') ~ 0x40('@')
        throw new IllegalArgumentException("wrong ascii: " + ascii);
    }

    if (ascii <= 0x46) { // 0x41('A') ~ 0x46('F')
        return ascii - 0x37; // 0x0A, 0x0B, ...
    }

    if (ascii <= 0x60) { // 0x47('G') ~ 0x60('`')
        throw new IllegalArgumentException("wrong ascii: " + ascii);
    }

    if (ascii <= 0x66) { // 0x61('a') ~ 0x66('f')
        return ascii - 0x57; // 0x0A, 0x0B, ...
    }

    // 0x67('g') ~
    throw new IllegalArgumentException("wrong ascii: " + ascii);
}
/**
 * Converts a 4-bit unsigned integer to a single 7-bit ASCII value. An
 * <code>IllegalArgumentException</code> will be thrown if given
 * <code>integer</code> is in wrong range.
 *
 * @param integer 4-bit unsigned integer (0x00 ~ 0x0F)
 * @return 7-bit ASCII value; digit (0x30 ~ 0x39) or upper alpha (0x41 ~ 0x46)
 */
static int itoa(final int integer) {

    if (integer < 0x00) {
        throw new IllegalArgumentException("wrong integer: " + integer);
    }

    if (integer <= 0x09) { // 0x00 ~ 0x09
        return integer + 0x30; // 0x48('0'), 0x49('1'), ...
    }

    if (integer <= 0x0F) { // 0x0A ~ 0x0F
        return integer + 0x37; // 0x41('A'), 0x42('B'), ...
    }

    throw new IllegalArgumentException("wrong integer: " + integer);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s