Каково различие между простым текстом и двоичными данными?

Если можно получить указатель на члена класса, можно использовать указатель, неважно, что спецификаторы доступа (даже методы).

class X;
typedef void (X::*METHOD)(int);

class X
{
    private:
       void test(int) {}
    public:
       METHOD getMethod() { return &X::test;}
};

int main()
{
     X      x;
     METHOD m = x.getMethod();

     X     y;
     (y.*m)(5);
}

, Конечно, мой любимый небольшой взлом является другом шаблонный черный ход.

class Z
{
    public:
        template<typename X>
        void backDoor(X const& p);
    private:
        int x;
        int y;
};

Принятие создателя вышеупомянутого определило бэкдор для его нормальной эксплуатации. Но Вы хотите получить доступ к объекту и посмотреть на переменные члена парламента, не занимающего официального поста. Даже если вышеупомянутый класс был скомпилирован в статическую библиотеку, можно добавить собственную шаблонную специализацию для бэкдора и таким образом получить доступ к участникам.

namespace
{
    // Make this inside an anonymous namespace so
    // that it does not clash with any real types.
    class Y{};
}
// Now do a template specialization for the method.
template<>
void Z::backDoor<Y>(Y const& p)
{
     // I now have access to the private members of Z
}

int main()
{
    Z  z;   // Your object Z

    // Use the Y object to carry the payload into the method.
    z.backDoor(Y());
}
16
задан pnuts 17 November 2015 в 09:02
поделиться

5 ответов

One thing it often means is that the language might feel free to interpret certian control characters, such as the values 10 or 13, as logical line terminators. In other words, an output operation might automagicly append these characters at the end, and an input operation might strip them from the input (and/or terminate reading there).

In contrast, language I/O operations that advertise working on "binary" data will usually include an input parameter for the length of data to operate on, since there is no other way (short of reading past end of file) to know when it is done.

4
ответ дан 30 November 2019 в 21:19
поделиться

a plain text is human readable, a binary file is usually unreadable by a human, since it's composed of printable and non-printable characters.

Try to open a jpeg file with a text editor (e.g. notepad or vim) and you'll understand what I mean.

A binary file is usually constructed in a way that optimizes speed, since no parsing is needed. A plain text file is editable by hand, a binary file not.

10
ответ дан 30 November 2019 в 21:19
поделиться

"Plaintext" can have several meanings.

The one most useful in this context is that it is merely a binary files which is organized in byte sequences that a particular computers system can translate into a finite set of what it considers "text" characters.

A second meaning, somewhat connected, is a restriction that said system should display these "text characters" as symbols readable by a human as members of a recognizable alphabet. Often, the unwritten implication is that the translation mechanism is ASCII.

A third, even more restrictive meaning, is that this system must be a "simple" text editor/viewer. Usually implying ASCII encoding. But, really, there is VERY little difference between you, the human, reading text encoded in some funky format and displayed by a proprietary program, vs. VI text editor reading ASCII encoded file.

Within programming context, your programming environment (comprized by OS + system APIs + your language capabilities) defines both a set of "text" characters, and a set of encodings it is able to read to convert to these "text" characters. Please note that this may not necessarily imply ASCII, English, or 8 bits - as an example, Perl can natively read and use the full Unicode set of "characters".

To answer your specific question, you can definitely use "character" strings to transmit arbitrary byte sequences, with the caveat that string termination conventions must apply. Проблема в том, что функции, которые уже существуют для «обработки символьных данных», вероятно, не будут иметь каких-либо полезных функций для работы с вашими двоичными данными.

7
ответ дан 30 November 2019 в 21:19
поделиться

Обычно это зависит от языка / среды / функциональности.

Двоичные данные всегда таковы: двоичные. Он передается без изменений.

Режим «Обычный текст» может означать одно или несколько из следующих действий:

  • поток байтов разбивается на строки. Разделителями строк являются \ r, \ n, \ r \ n или \ n \ r. Иногда это зависит от ОС (например, * nix любит \ n, а Windows любит \ r \ n). Конец строки может быть скорректирован для приложения чтения
  • , кодировка символов может быть скорректирована. Среда может обнаруживать и / или преобразовывать исходную кодировку в кодировку, ожидаемую приложением
  • , возможно, в этот список следует добавить некоторые другие преобразования, но в данный момент я не могу думать ни о чем
3
ответ дан 30 November 2019 в 21:19
поделиться

Технически ничего. Обычный текст - это форма двоичных данных. Однако основное различие заключается в том, как хранятся значения. Подумайте, как можно хранить целое число. В двоичных данных он будет использовать формат с дополнением до двух, вероятно, занимающий 32 бита пространства. В текстовом формате число будет храниться вместо этого как серия цифр Unicode. Таким образом, число 50 будет сохранено как 0x32 (заполнено до 32 бита) в двоичном формате, но будет сохранено как '5' '0' в обычном тексте.

3
ответ дан 30 November 2019 в 21:19
поделиться
Другие вопросы по тегам:

Похожие вопросы: