Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any Int24 implementations in C#?

Tags:

c#

types

I have a project that I am working on where I require a data type that doesn't exist in the .NET BCL - an Unsigned Int24. For calculations that I am doing, the 4th byte in an int32, even when set to all zeroes, screws up my results.

EDIT: I'm doing bitwise circular shifts on a 24bit integer space that is limited to only 24bits. If the rotation is performed at 24bit level on a 32bit number the result is wildly incorrect.

Does anyone know of any third party implementations of this data type that are available?

Thanks!

like image 467
TheNerd Avatar asked Feb 19 '23 02:02

TheNerd


1 Answers

Implementing Int24 isn't hard (honest!). But we need to know more about why you need to implement it. @nneonneo wonders if you're trying to interface with a native library that uses 24-bit integers. If that's the case then you can be done by doing something like this:

[StructLayout(LayoutKind.Sequential)]
public struct UInt24 {
    private Byte _b0;
    private Byte _b1;
    private Byte _b2;

    public UInt24(UInt32 value) {
        _b0 = (byte)( (value      ) & 0xFF );
        _b1 = (byte)( (value >>  8) & 0xFF ); 
        _b2 = (byte)( (value >> 16) & 0xFF );
    }

    public unsafe Byte* Byte0 { get { return &_b0; } }

    public UInt32 Value { get { return _b0 | ( _b1 << 8 ) | ( _b2 << 16 ); } }
}

// Usage:

[DllImport("foo.dll")]
public static unsafe void SomeImportedFunction(byte* uint24Value);

UInt24 uint24 = new UInt24( 123 );
SomeImportedFunction( uint24.Byte0 );

Modifying the class for big-endian or signed Int24 is an exercise left up to the reader.

like image 139
Dai Avatar answered Feb 27 '23 03:02

Dai