Define 24 Bit data type

S

stuie_norris

Hi Group,

I have had a go at defining a data type for handle 3 byte data (24
Bit). I want to be able to
use the datatype like a normal datatype such as int, short etc. Plus
I wish to have some extra
methods that allow me get specific bytes if needed.

Here is what I have tried.

using System;
using System.Collections.Generic;
using System.Text;

namespace mytype
{
class Program
{
static void Main(string[] args)
{
byte[] a = new byte [3];
byte[] b = { 0x1, 0x2, 0x3 };

Bit24 bit24 = b;
a = bit24;

byte byte1 = bit24.setbyte(1, 0x01);
byte byte2 = bit24.getbyte(1);
}
}

public class Bit24
{
private byte[] _value = new byte[3];
public Bit24(byte[] value)
{
_value = value;
}
public byte getbyte(int field)
{
return _value[field];
}
public byte setbyte(int field, byte value)
{
_value[field] = value;
}
}
}

Thanks

Stuart
 
J

Jon Skeet [C# MVP]

I have had a go at defining a data type for handle 3 byte data (24
Bit). I want to be able to
use the datatype like a normal datatype such as int, short etc. Plus
I wish to have some extra
methods that allow me get specific bytes if needed.

Here is what I have tried.

<snip>

It's not clear what your question is. However, some suggestions:
1) Don't use an array - that's adding pointless overhead. Just have
three byte members.
2) If you want your type to behave like other value types (int, short
etc) then your type should be a value type too - make it a struct
3) Mutable structs generally cause confusion - make methods which
return a new instance of your type based on a previous instance and a
modification, rather than allowing the existing value to be modified.

If that doesn't help, please specify what you're trying to achieve
that your current code doesn't achieve.

Jon
 
S

stuie_norris

Hi Jon,

Thanks for the response. I am trying to make a datatype that works
with byte arrays like int so I am work with 3 byte data and 80 byte
data.

1) What do you mean with have a three byte member?

public class Bit24
{
private byte[] _value = new byte[3]; - You mean change this
to what
....
}


2) and 3) Yep. Point taken

Thanks

Stuart
 
J

Jon Skeet [C# MVP]

Thanks for the response. I am trying to make a datatype that works
with byte arrays like int so I am work with 3 byte data and 80 byte
data.

In that case calling it "Bit24" is a bad idea.
1) What do you mean with have a three byte member?

public class Bit24
{
private byte[] _value = new byte[3]; - You mean change this
to what
...
}

If you *know* it'll only be 3 bytes, just make:

public class Bit24
{
byte byte0;
byte byte1;
byte byte2;
}

(Or something like that.)

It doesn't need to affect the public API.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top