Как ввести символы неASCII в строковый литерал в C/C++

Вам нужен уникальный ключ id в вашей таблице (предположим, что его значение равно 1), чтобы сделать что-то вроде:

UPDATE table1 SET col1="hello" WHERE id=1 AND col1!="hello"
7
задан 8 June 2009 в 18:16
поделиться

8 ответов

Use an escape sequence. Make sure you put the characters in the correct order.

"\x01\x02\x03\x04"

Edit: If you need to put the sequence into an existing char array, simply assign it in.

char s[4];

// ... later ...
s[0] = 0x01;
s[1] = 0x02;
s[2] = 0x03;
s[3] = 0x04;

Do not attempt to assign the number by casting s to (int32_t *), the char array doesn't have the correct alignment.

17
ответ дан 6 December 2019 в 06:14
поделиться

Probably the easiest, in C, is to use the hex escape notation: "\x01\x02\x03\x04". (Without the x, the values are in octal, which isn't nearly as popular or understandable nowadays.)

Alternatively,

char x[] = {1, 2, 3, 4, 0};

should work (notice that the null termination has to be included when initializing like this).

4
ответ дан 6 December 2019 в 06:14
поделиться

Хорошо, вы уверены, что вам нужен строковый литерал?

Все они очень похожи:

const char* blah = "test";
char blah[] = "test";
char blah[] = { 't','e','s','t',0 };

Вы, конечно, можете легко использовать третью форму для своих нужд.

2
ответ дан 6 December 2019 в 06:14
поделиться

Мне нужно, чтобы значение строки в памяти было равно шестнадцатеричному значению 0x01020304, которое все не является символами ASCII.

будьте осторожны Как расположены 4 последовательных байта в памяти будет зависеть от того, является ли ваша система прямым или прямым порядком байтов. Если вас волнует, как работает 32-битное поле, просто поместить данные в строковый литерал не получится.

Например:

Вы можете попробовать, как предлагает avakar:

char cString[5] = "\x01\x02\x03\x04";

или даже просто сделать

cString[0] = 0x01;
cString[1] = 0x02;
...

но если вы ожидаете, что реальная физическая структура в памяти будет иметь смысл:

// assuming unsigned int is 32 bits
unsigned int* cStringAlias = rentirpret_cast<int*>(&cString[0]);
std::cout << (*cStringAlias)

Будьте осторожны , вывод будет отличаться в зависимости от того, находится ли старший байт в 0-м месте или в 3-м месте.

Вывод может быть

0x01020304

или

0x04030201

Подробнее см. О endianess .

3
ответ дан 6 December 2019 в 06:14
поделиться

Save the source in UTF8 and treat all strings as UTF-8 (or use something line StringFromUTF()).

Each time you don't work in an universal code page (yes, UTF-8 is not really a code page...) you are asking for troubles.

1
ответ дан 6 December 2019 в 06:14
поделиться

When writing C code, you can use memcpy() to copy binary data:

memcpy(dest + offset, src, 4);

If src is a string, you presumably get it in the right order. If it's an integer (say, uint32_t) and you need a specific endianness, you might need to reverse the order of the bytes before doing memcpy():

uint32_t src;

...

swap((unsigned char *) &src, 0, 3);
swap((unsigned char *) &src, 1, 2);

where swap() is defined by you. You must do this only if the machine endianness doesn't match the desired output endianness.

You can discover the endianness by looking at certain defines set by the compiler or C library. At least on glibc (Linux), endian.h provides such definitions, and byteswap.h also provides byte-swapping functions.

1
ответ дан 6 December 2019 в 06:14
поделиться

Вы можете использовать std :: wcin и std :: wcout для поддержки Unicode для консоли. Однако я не уверен, являются ли они частью стандарта.

0
ответ дан 6 December 2019 в 06:14
поделиться

You may want to try using std::hex:

int temp;
char sentMessage[10];
        for(int i = 0; i < 10; ++i)
        {
            std::cin >> std::hex >> temp;
            sentMessage[i] = temp;   
        } 

You would then type in the hexadecimal value of each character, eg. 01 11 7F AA

0
ответ дан 6 December 2019 в 06:14
поделиться