0

I am trying to print stored bitmap images in some printers. The program is a Windows Form. The command to print the logo (bitmap)-(if there is one stored) is:

port.Write("\x1C\x70\x01\x00");

('port' being my name for new serial port object).

There can be from 0 to 255 DEC (00 to FF HEX) different locations in the printers memory. I need a for loop or while loop that will increment the above line of code so,

port.Write("\x1C\x70\x01\x00"); would become
port.Write("\x1C\x70\x02\x00");
port.Write("\x1C\x70\x03\x00"); up to FF
port.Write("\x1C\x70\xFF\x00");

etc etc.

I looked on MSDN & Search Stack Overflow:

Cœur
  • 37,241
  • 25
  • 195
  • 267
Daniel Steele
  • 33
  • 1
  • 1
  • 7
  • Note that `"\x1C\x70\x01\x00"` is not a hex string, it's a regular string made up of regular character literals where you have used a [hexedecimal escape sequence](https://msdn.microsoft.com/en-us/library/aa691087(v=vs.71).aspx) to declare the characters. – Quantic Apr 11 '17 at 19:12

2 Answers2

2

Also, as an alternative to Coriths solution. The SerialPort object lets you write a byte array directly, rather than converting your bytes to a string that the SerialPort then converts back into bytes again.

for (byte i = 0; i < 255; i++)
{
    var bytes = new byte[] { 0x1C, 0x70, i, 0x00 };
    port.Write(bytes, 0, 4);
}
MrZander
  • 3,031
  • 1
  • 26
  • 50
0

This loop should work for you. You can always use 0x to work in hexadecimal numbers in your loops.

for(var c = 0x01; c <= 0xFF; c++)
{
  port.Write($"\x1C\x70\x{c:X2}\x00");
}
Corith Malin
  • 1,505
  • 10
  • 18
  • `"\x1C\x70\x01\x00"` doesn't equal `"\x1C\x70" + 0x01 + "\x00"`. For example, `"\x41"` is the Unicode character `A` but `0x41` is just the number `65`. – Quantic Apr 11 '17 at 19:11
  • Quantic, give the edit a try. I don't have immediate access to a compiler, but I didn't quite see that you were trying to output unicode characters. This should lead you down the right path but I can still help if you have other questions. – Corith Malin Apr 11 '17 at 19:27
  • I'm not the asker, but I'm pretty sure they have a similar issue where even with your fixed code they aren't actually getting the output they are expecting – Quantic Apr 11 '17 at 19:30
  • second answer generates an error "Unrecognized escape sequence" – Daniel Steele Apr 11 '17 at 19:33
  • 1st answer does work. Thank you to everyone that helped! – Daniel Steele Apr 12 '17 at 15:49