1

I would like to print some 0xff bytes using Python 3.5.2 to pipe them into another program. I have a simple C program which reads from stdin and prints each char in hex:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main () {
    char *buffer = malloc(0x100);
    fgets(buffer, 0x100, stdin);
    for (int i = 0; buffer[i] != 0; printf("%x ", buffer[i++]));
}

If I echo 0xff byte and pipe it into my program, chars are displayed as expected (a is because of newline):

# echo -e "\xff\xff\xff\xff" | ./print-chars
ffffffff ffffffff ffffffff ffffffff a

I can also do it with Perl:

# perl -e 'print "\xff\xff\xff\xff"' | ./print-chars
ffffffff ffffffff ffffffff ffffffff

But when I try it in python, the result is different:

 # python -c 'print("\xff\xff\xff\xff")' | ./print-chars
ffffffc3 ffffffbf ffffffc3 ffffffbf ffffffc3 ffffffbf ffffffc3 fffffbf a

My questions:

  • Why does Python print 0xc3 and 0xb3 bytes instead of 0xff?
  • What is the proper way of printing 0xff using Python (I want to achieve the same result as with echo or Perl)?
Daew
  • 419
  • 1
  • 4
  • 14
  • Thank you, `sys.stdout.buffer.write(b"\xff\xff\xff\xff")` works perfectly – Daew Nov 26 '16 at 19:40
  • As an aside: Declare `buffer` as `unsigned char *buffer` to avoid the erroneous leading `ffffff`-s. –  Nov 26 '16 at 22:10
  • @duskwuff: thank you for suggestion, I only included this code to demonstrate what the output of Python's `print` is, it is not actual code that I use anywhere – Daew Nov 27 '16 at 18:04
  • What you're seeing is the result of encoding: `'\xff\xff\xff\xff'.encode()` returns `b'\xc3\xbf\xc3\xbf\xc3\xbf\xc3\xbf'`. The last `a` corresponds to the newline character. – vaultah Nov 30 '16 at 06:42

1 Answers1

-1

One of the way is use struct module to pack a values into binary string:

import struct
value = 0xFF
s = struct.pack('B', value)
print(s)
list_of_values = [255]*4
s = struct.pack('4B', *list_of_values)
print(s)

will give next output:

b'\xff'
b'\xff\xff\xff\xff'
JOHN_16
  • 616
  • 6
  • 12
  • ... which is the same as the output of `print(bytes([255] * 4))`, which when piped into OP's C program becomes `62 27 5c 78 66 66 5c 78 66 66 5c 78 66 66 5c 78 66 66 27 a`. – vaultah Nov 30 '16 at 06:57