C# help padding Byte with zeros

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Maja Gajic
    New Member
    • Jul 2011
    • 3

    C# help padding Byte with zeros

    Hello I am quiet new at C# programming so would appreciate any help. I am writing a program to communicate via RS232 with a machine and need to send it a packet in the form:
    Code:
    { <DLE> , <STX> , "G" , <DLE> , <ETX> , <CRC> , <CRC> }
    
    byte[] byteToSend = new byte[] { 0x10, 0x02, 0x47, 0x10, 0x03, CRC , CRC };
    My two byte CRC is 0x421F and I need to split it into two bytes to fit the format above.
    When I convert to binary I get < 01000010 | 00011111 >
    Obviously the left zero padding on the MSB doesn't matter but the padding on the LSB is important and I think converting it into < 0x42 | 0x1F > is not correct as it loses the zero padding on the LSB.

    Thanks for any help
    Maja :)
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    It shouldn't matter, it's still a byte. I assume you're printing out the value with Convert.ToStrin g(0x1F, 2)? If so, that's the correct output it's just not padded with zeros. Have a look at the following...

    I take the full value, split it into high and low bytes, then rebuild it to get the same value I started with. The information should be preserved :)

    Code:
    static void Main(string[] args)
    {
        short CRC_raw = 0x421F;
        byte CRC_high;
        byte CRC_low;
        short CRC_rebuilt;
    
        Console.WriteLine("    Raw: " + ToHex(CRC_raw) + " -- " + ToBinary(CRC_raw));
    
        CRC_low = (byte)(CRC_raw & (short)0x00FF);
        CRC_high = (byte)(CRC_raw >> 8);
    
        Console.WriteLine("    Low: " + ToHex(CRC_low) + " -- " + ToBinary(CRC_low));
        Console.WriteLine("   High: " + ToHex(CRC_high) + " -- " + ToBinary(CRC_high));
    
        CRC_rebuilt = (short)(((0x0000 | CRC_high) << 8) | CRC_low);
    
        Console.WriteLine("Rebuilt: " + ToHex(CRC_rebuilt) + " -- " + ToBinary(CRC_rebuilt));
    }
    
    static string ToHex(int val)
    {
        return "0x" + val.ToString("X");
    }
    
    static string ToBinary(int val)
    {
        return Convert.ToString(val, 2);
    }
    Output:
    Raw: 0x421F -- 100001000011111
    Low: 0x1F -- 11111
    High: 0x42 -- 1000010
    Rebuilt: 0x421F -- 100001000011111

    Comment

    • Maja Gajic
      New Member
      • Jul 2011
      • 3

      #3
      Great that makes more sense now, Thanks for the clever code!

      Comment

      Working...