Skip to content

Instantly share code, notes, and snippets.

@FlorianWolters
Last active August 10, 2024 18:15
Show Gist options
  • Save FlorianWolters/be839c84991a789df1c6 to your computer and use it in GitHub Desktop.
Save FlorianWolters/be839c84991a789df1c6 to your computer and use it in GitHub Desktop.
C++ source code snippets

C++ source code snippets

Represent one byte

using Byte = std::uint8_t;

Represent a dynamic number of bytes

#include <vector>

using ByteVector = std::vector<std::uint8_t>;

Create a std::vector from a std::stringstream

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main() {
  std::stringstream stream{"hello, world\0"};
  std::string const kString{stream.str()};
  std::vector<std::uint8_t> const kVector{kString.begin(), kString.end()};

  // Test
  for (auto const kByte : kVector) {
    std::cout << kByte;
  }
}

Write a std::vector to a std::ostream

Using std::streambuf::pubsetbuf

#include <iostream>
#include <sstream>
#include <vector>

int main() {
  std::vector<std::uint8_t> vector{'a', 'b', 'c'};
  std::stringstream stream;
  //stream.rdbuf()->pubsetbuf(reinterpret_cast<char *>(&vector[0]), vector.size());
  stream.rdbuf()->pubsetbuf(reinterpret_cast<char *>(kVector.data()), kVector.size());

  // Test
  std::cout << stream.str();
}

Using std::copy

#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

int main() {
  std::vector<std::uint8_t> vector{'a', 'b', 'c'};
  std::stringstream stream;
  std::copy(vector.begin(), vector.end(), std::ostream_iterator<std::uint8_t>(stream));

  // Test
  std::cout << stream.str() << "\n";
}

Using std::ostream.write

#include <iostream>
#include <vector>

void write_vector_to_ostream(std::ostream &ostream, std::vector<std::uint8_t> const &kVector) {
  ostream.write(reinterpret_cast<char const *>(kVector.data()), kVector.size());
}

int main() {
  // Test
  write_vector_to_ostream(std::cout, std::vector<std::uint8_t>{'a', 'b', 'c'});
}

Implementing << for std::vector

#include <iostream>
#include <iterator>
#include <vector>

template <typename T>
std::ostream& operator<<(std::ostream& os, std::vector<T> const& kVector) {
  std::copy(kVector.begin(), kVector.end(), std::ostream_iterator<T>(os));

  return os;
}

int main() {
  std::vector<std::uint8_t> const kVector{'a', 'b', 'c'};

  // Test
  std::cout << kVector << "\n";
}

Serialization

Receive "raw" data via a network socket using Boost.Asio

The length should be equal to the length of the expected message if possible.

char d1[128];
size_t bytes_transferred = sock.receive(boost::asio::buffer(d1));

std::vector<char> d2(128);
bytes_transferred = sock.receive(boost::asio::buffer(d2));

std::array<char, 128> d3;
bytes_transferred = sock.receive(boost::asio::buffer(d3));

boost::array<char, 128> d4;
bytes_transferred = sock.receive(boost::asio::buffer(d4));

Convert "raw" data to a std::istream

boost::asio::streambuf b;

// reserve 512 bytes in output sequence
boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(512);

size_t n = sock.receive(bufs);

// received data is "committed" from output sequence to input sequence
b.commit(n);

std::istream is(&b);
std::string s;
is >> s;

Deserialize an object from a std::istream

Must be implemented for each class, e.g. via a DeserializableAbstract class or via external classes (preferred).

Pseudo code:

// `is` contains an input stream:
std::string last_name;
std::string first_name;
std::uint16_t age;

is >> last_name;
is >> first_name;
is >> age;

Person person{last_name, first_name, age};

Container

std::vector

Initializing a std::vector

<used_std> > C++11
std::vector<std::uint8_t> const kBytes{'a', 'b', 'c'};
<used_std> < C++11
std::uint8_t const kBytesAsArray[] = {'a', 'b', 'c'};

std::vector<std::uint8_t> const kBytes(
    kBytesAsArray,
    kBytesAsArray + sizeof(kBytesAsArray) / sizeof(kBytesAsArray[0]));
@Khalaf2003
Copy link

#include
#include
#include

std::map<char, std::string> charToMorse = {
{'A', ".-"}, {'B', "-..."}, {'C', "-.-."}, {'D', "-.."}, {'E', "."},
{'F', "..-."}, {'G', "--."}, {'H', "...."}, {'I', ".."}, {'J', ".---"},
{'K', "-.-"}, {'L', ".-.."}, {'M', "--"}, {'N', "-."}, {'O', "---"},
{'P', ".--."}, {'Q', "--.-"}, {'R', ".-."}, {'S', "..."}, {'T', "-"},
{'U', "..-"}, {'V', "...-"}, {'W', ".--"}, {'X', "-..-"}, {'Y', "-.--"},
{'Z', "--.."}, {'1', ".----"}, {'2', "..---"}, {'3', "...--"}, {'4', "....-"},
{'5', "....."}, {'6', "-...."}, {'7', "--..."}, {'8', "---.."}, {'9', "----."},
{'0', "-----"}
};

std::map<std::string, char> morseToChar;

void initializeMorseToCharMap() {
for (auto& pair : charToMorse) {
morseToChar[pair.second] = pair.first;
}
}

std::string textToMorse(const std::string& text) {
std::stringstream result;
for (char c : text) {
if (c == ' ') {
result << " "; // Three spaces between words
} else {
result << charToMorse[toupper(c)] << " ";
}
}
return result.str();
}

std::string morseToText(const std::string& morse) {
std::stringstream result;
std::stringstream morseStream(morse);
std::string token;
while (morseStream >> token) {
if (token == " ") {
result << " "; // Space between words
} else {
result << morseToChar[token];
}
}
return result.str();
}

int main() {
initializeMorseToCharMap();

std::string plainText = "I love C plus plus";
std::string morseText = textToMorse(plainText);
std::cout << "Plain text: " << plainText << std::endl;
std::cout << "Morse text: " << morseText << std::endl;

std::string decodedText = morseToText(morseText);
std::cout << "Decoded text: " << decodedText << std::endl;

return 0;

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment