简体   繁体   中英

Byte conversion from 32 bit to 8 bit

hi this I want to send this hex vales but i am getting error.. I am send byte values ,** my error.. constant vales cannot be converted to byte.**

class constant(){
public const byte MESSAGE_START = 0x1020; // command hex
}


public override IEnumerable<byte> ToBytes()
        {
      yield return constant.MESSAGE_START ;

    }

HI, there is another twist i am facing, though with your help I passed the hex value, I should decimal equivalent when i pass through the below method, but value I get is 16.

protected override void TransmitCommand(Device device, Command command) { int count = 0;

        foreach (var b in command.ToBytes())
            transmitBuffer[count++] = b;   // values i get is 16 but not decimal values 4128
    }

As I said in the comment, the value MESSAGE_START is a short not a byte . Try this

class constant() {
  public const short MESSAGE_START = 0x1020; // command hex
}

public override IEnumerable<byte> ToBytes()
{
  yield return (byte) (constant.MESSAGE_START >> 8);
  yield return (byte) (constant.MESSAGE_START & 0xff);
}

The above code assumes that the byte representation of the value is in network byte order (most significant byte first). For LSB do

public override IEnumerable<byte> ToBytes()
{
  yield return (byte) (constant.MESSAGE_START & 0xFF);
  yield return (byte) (constant.MESSAGE_START >> 8);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM