1 message in net.java.dev.jna.usersUnsigned debate
FromSent OnAttachments
Paul LoyApr 2, 2008 1:35 pm 
Actions with this message:
Paste this link in email or IM:
Paste this link in email or IM:
Atom feed for this thread
Paste this URL into your reader:
Subject:Unsigned debateActions...
From:Paul Loy (kete@gmail.com)
Date:Apr 2, 2008 1:35:12 pm
List:net.java.dev.jna.users

Hi Timothy et al,

So I've finally come up to a point where a mapping of unsigned shorts (in this case) is needed.

Here's my first cut at an UnsignedIntegerType. I extended IntegerType, although I think that it could be a lot smarter if IntegerType was a base class with SignedIntegerType and UnsignedIntegerType extensions. Then, some things would fall out by either Reflection or Generics, and the rest can be implementation detail.

import com.sun.jna.FromNativeContext; import com.sun.jna.IntegerType;

public abstract class UnsignedIntegerType extends IntegerType {

private final long MAX_VALUE;

public UnsignedIntegerType(int size) { this(size, 0); }

public UnsignedIntegerType(int size, long value) { super(size); if (size > 4) throw new UnsupportedOperationException( "We will need a LongLong in Java to express the maximum end " + "of an unsigned long or bigger. You can always implement " + "your own big number class to deal with this if needed.");

MAX_VALUE = (long) Math.pow(2, size*8); setValue(value); }

@Override public void setValue(long value) { if (value > (MAX_VALUE/2)) value -= MAX_VALUE; super.setValue(value); }

@Override public Object fromNative(Object nativeValue, FromNativeContext context) { long value = nativeValue == null ? 0 : ((Number) nativeValue).longValue();

try { UnsignedIntegerType number = getClass().newInstance(); number.setValue(value); return number; } catch (InstantiationException e) { throw new IllegalArgumentException("Can't instantiate " + getClass()); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Not allowed to instantiate " + getClass()); } }

}

Obviously, I could just have a convert util method somewhere to convert between a signed and unsigned java primitive (along with upscaling the primitive as java is signed). But it would be nice to just define a structure or return type and not have to worry about converting.

Anywho, discussion open!

Paul.