Java Hex String Create appendHex(StringBuilder buf, int value, int width)

Here you can find the source of appendHex(StringBuilder buf, int value, int width)

Description

Converts the passed value into hexadecimal representation, and appends that representation to the buffer, left-zero-padded.

License

Apache License

Parameter

Parameter Description
buf The buffer to be updated.
value The value to be converted.
width Size of the field that will hold the value. If the hex representation of the value is smaller, it will be left-zero-padded; if greater, the high-order bits will be truncated.

Declaration

public static StringBuilder appendHex(StringBuilder buf, int value, int width) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

public class Main {
    private final static char[] NIBBLES = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
            'C', 'D', 'E', 'F' };

    /**//from   w w w.java 2s .c  om
     *  Converts the passed value into hexadecimal representation, and appends
     *  that representation to the buffer, left-zero-padded.
     *
     *  @param buf      The buffer to be updated.
     * @param value    The value to be converted.
     * @param width    Size of the field that will hold the value. If the hex
     *                  representation of the value is smaller, it will be
     *                  left-zero-padded; if greater, the high-order bits will
     *                  be truncated.
     */
    public static StringBuilder appendHex(StringBuilder buf, int value, int width) {
        appendRepeat(buf, '0', width);
        int offset = buf.length();
        for (int ii = 1; ii <= width; ii++) {
            int nibble = value & 0xF;
            buf.setCharAt(offset - ii, NIBBLES[nibble]);
            value >>>= 4;
        }

        return buf;
    }

    /**
     *  Appends N copies of the same character to the end of a builder.
     */
    public static StringBuilder appendRepeat(StringBuilder buf, char c, int count) {
        buf.ensureCapacity(buf.length() + count);
        for (int ii = 0; ii < count; ii++)
            buf.append(c);
        return buf;
    }
}

Related

  1. appendHex(StringBuffer buffer, int value)
  2. appendHex(StringBuffer sb, byte b)
  3. appendHex(StringBuffer sbuf, char ch)
  4. appendHex(StringBuffer stringbuffer, byte byte0)
  5. appendHex(StringBuilder bld, byte b)
  6. appendHex(StringBuilder buff, int i)
  7. appendHex(StringBuilder builder, int b)
  8. appendHexByte(byte b, StringBuffer buf)
  9. appendHexByte(final StringBuilder sb, final byte b)