Skip to content

Commit 36bf4da

Browse files
committed
cpp: uint8_t to string
1 parent f8171dd commit 36bf4da

1 file changed

Lines changed: 24 additions & 2 deletions

File tree

‎cpp/string.cpp‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ int main() {
3434
//
3535
// Creates a new string.
3636
//
37-
// The only way to do inline this without creating a new string seems to be by using stringstream.
37+
// The only way to do to it in-place without creating a new string seems to be by using stringstream:
3838
// http://stackoverflow.com/questions/662918/how-do-i-concatenate-multiple-c-strings-on-one-line
3939
{
4040
std::string s = "ab";
@@ -73,7 +73,7 @@ int main() {
7373

7474
// # c_str
7575
//
76-
// Convert std::string to C null terminated char* string.
76+
// Convert std::string to C null terminated char* string.
7777
{
7878
std::string s = "abc";
7979
assert((std::strcmp(s.c_str(), "abc")) == 0);
@@ -248,4 +248,26 @@ int main() {
248248
assert(std::stoi("123") == 123);
249249
#endif
250250
}
251+
252+
// String from bytes.
253+
// std::string is just basic_string with char type, so easy for char:
254+
// https://stackoverflow.com/questions/1673445/how-to-convert-unsigned-char-to-stdstring-in-c
255+
//
256+
// uint8_t:
257+
// https://stackoverflow.com/questions/4508911/convert-uint8-t-to-stdstring-in-c
258+
{
259+
// Null terminated.
260+
{
261+
uint8_t bytes[]{'a', 'b', 'c', '\0'};
262+
std::string s((const char*)bytes);
263+
assert(s == std::string("abc"));
264+
}
265+
266+
// Explicit length.
267+
{
268+
uint8_t bytes[]{'a', 'b', 'c'};
269+
std::string s((const char*)bytes, 3);
270+
assert(s == std::string("abc"));
271+
}
272+
}
251273
}

0 commit comments

Comments
 (0)