com.genedavis.util.GDBytes

This class is for the converting of unsigned bytes, represented by ints to signed bytes or going the other direction, signed to unsigned.

Java lives up to the Perl mantra of making simple things easy and hard things possible. One example is network protocol implementation. If you’ve implemented one in java, you’ve probably dealt with the small number of primative types that Java offers over c or c++. Normally this is a plus, IMHO, but not when doing low level work. Signed byte to unsigned byte conversions, or visa-versa, are the most used low level trick you’ll need.

You can use these two static methods to do the conversion, or just look at the source and copy the code. It’s not much code, just not well documented in most Java textbooks that I’ve seen.

//  GDBytes.java
//
//  Created by Gene Davis on Sat Aug 18 2001.

package com.genedavis.util;

public class GDBytes {

    /**
     * Turns a signed byte, represented as a byte primative, 
     * into an unsigned byte, represented by an int.
     *
     * @param b a primative byte to be converted to an unsigned byte.
     * 
     * @return int representing a signed byte.
     */
    public static int signedByteToUnsignedByte(byte b) {
        return (0xff & b);
    }

    /**
     * Turns an unsigned byte, represented as an int primative, 
     * into an signed byte, represented by an byte primative.
     *
     * @param i a primative int to be converted to a signed byte.
     * 
     * @return byte in java is always signed.
     */
    public static byte unsignedByteToSignedByte(int i) {
        return (byte) i;
    }

}