Harry Cho
Harry Cho

Reputation: 2529

how to stdin any byte (0-255)?

I have a very simple following code which gets 4 bytes from stdin and prints them out byte by byte in hex format.

// Code may be different but the point is to input any byte value 0 to 255 from stdin 
int main(int argc, char** argv) {
    char buffer[4];
    read(0, buffer, 4); // or gets(buffer)
    int i;
    for(i = 0; i < 4; i++) {
        printf("%x", buffer[i]);
    }
}

The problem I am encountering is that I am limited by what I can type through keyboard so I cannot supply any byte to stdin. For example, if I am dealing with ACSII, it is not possible to give 0x11 because ASCII 0x11 is Device Control 1 (oft. XON) which keyboard does not have. I have more problem if I am dealing with UTF-8 because characters does not use full range of byte (it goes up to 0x7f and start to use 2 bytes).

I am looking for something like "\x11\x11\x11\x11" in C style string or constant format like 0x11111111 in C.

What ways are there to give any byte 0-255 to stdin so that I have full control on what value goes to the buffer?

EDIT : I am on a system where I do not have a privilege to create a file.

Sadly, I've been stuck on this for a week now. Thank you very much!.

Upvotes: 1

Views: 2558

Answers (2)

Keiji
Keiji

Reputation: 1042

Firstly it's worth knowing that your keyboard can send all codes between 32 and 126.

To get codes between 0 and 31, as well as the code 127, you can use the following method on any typical terminal such as gnome-terminal on Linux or PuTTY on Windows:

First, press Ctrl+V. This tells the terminal to send the next thing you type as a literal character. You can now type any of the following:

  • For a value between 1 and 26, press Ctrl+A through Ctrl+Z.
  • For a value between 27 and 31, press Ctrl+3 through Ctrl+7. You must use the numbers above the letters - do not use the number pad.
  • For the value 127, press Ctrl+8.
  • For the value 0, press Ctrl+@. (On a US keyboard this means Ctrl+Shift+2, on a UK keyboard it's Ctrl+Shift+apostrophe.)

This lets you type any character (below 128) in the middle of ordinary typing (whereas programs like printf as suggested by gabber, do work but you cannot use them if you want to type normally before and after your special characters).

To get characters 128 and above, if you're using PuTTY, you can set the encoding to CP437 (or the like) and copypaste the characters from the table at Wikipedia. Outside of PuTTY I'm not sure how you'd manage this.

Upvotes: 4

gabber
gabber

Reputation: 100

Based on this SO you can type the following for ASCII codes 0-255:

printf "\x$(printf %x 11)" | yourprogram

Change 11 to any ASCII code you need.

Upvotes: 0

Related Questions