Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "\x" work in a String?

Tags:

c++

c

hex

I'm writing a C/C++ program that involves putting a hex representation of a number into a string and I'm confused as to how \x works. I've seen examples where people have written things such as "\xb2". In this case, how does the program know if you want the hex of b followed by the number 2 or if you want the hex of b2? Additionally, when it stores this into memeory does it save the "\x" characters or does it just save the hex representation?

like image 787
Nosrettap Avatar asked Apr 07 '12 18:04

Nosrettap


People also ask

What does STD string do?

std::string is a typedef for a particular instantiation of the std::basic_string template class. Its definition is found in the <string> header: using string = std::basic_string<char>; Thus string provides basic_string functionality for strings having elements of type char.

What is a string in programming?

Most programming languages have a data type called a string, which is used for data values that are made up of ordered sequences of characters, such as "hello world". A string can contain any sequence of characters, visible or invisible, and characters may be repeated.


3 Answers

When you use the escape sequence \x inside a string the data following the \x is actually stored in it's binary representation.

So the string "ABC" is equivalent to the string "\x414243"

If you want to emit hexadecimal values in display-character form, you'll want to use the %x or %X format specifier character:

printf("%X%X%X", 'A', 'B', 'C');    // emits "414243"

See Section 1.2.6 and Section 1.2.7 of the C Library Reference Guide

Hope that explanation helps.

like image 82
Robert Groves Avatar answered Sep 25 '22 18:09

Robert Groves


As an example, the string "123\x45" is stored in hex as 31 32 33 45.

As per Oli's answer, the longest valid value after the '\x' is used.

The '\x' is not stored. Any escape sequence does not store the characters you see on the screen, it stores the actual character specified. For example, '\n' is actually stored as a linefeed character, 0x0A.

like image 29
Kendall Frey Avatar answered Sep 26 '22 18:09

Kendall Frey


From the C99 standard (6.4.4.4):

Each octal or hexadecimal escape sequence is the longest sequence of characters that can constitute the escape sequence.

like image 34
Oliver Charlesworth Avatar answered Sep 23 '22 18:09

Oliver Charlesworth