ATLAS Offline Software
Loading...
Searching...
No Matches
binStrToHexStr.h
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
3*/
4
5#ifndef GLOBALSIM_BINSTRTOHEXSTR_H
6#define GLOBALSIM_BINSTRTOHEXSTR_H
7
8#include <algorithm>
9#include <ranges>
10#include <stdexcept>
11#include <string>
12#include <string_view>
13
14namespace GlobalSim {
15
16 constexpr char
17 hexChar(std::string_view bits){
18 unsigned int value{};
19 for (const char c : bits) {
20 value = (value << 1) | (c == '1');
21 }
22 return (value < 10) ? static_cast<char>('0' + value) : static_cast<char>('a' + value - 10);
23 }
24
25 inline std::string
26 binStrToHexStr(std::string_view s){
27 if (s.starts_with("0b") || s.starts_with("0B")) {
28 s.remove_prefix(2);
29 }
30 if (s.empty()) {
31 return {};
32 }
33 if (!std::ranges::all_of(s, [](char c) { return c == '0' || c == '1';})) {
34 throw std::invalid_argument("binary string contains non-binary character");
35 }
36 std::string result;
37 result.reserve((s.size() + 3) / 4);
38 const auto firstGroupSize = s.size() % 4;
39 std::size_t pos{};
40 if (firstGroupSize != 0) {
41 result.push_back(hexChar(s.substr(0, firstGroupSize)));
42 pos = firstGroupSize;
43 }
44 for (; pos < s.size(); pos += 4) {
45 result.push_back(hexChar(s.substr(pos, 4)));
46 }
47 return result;
48 }
49
50} // namespace GlobalSim
51
52#endif
AlgTool to read in LArStripNeighborhoods, and run the BDT Algorithm.
Definition BitSpec.h:23
std::string binStrToHexStr(std::string_view s)
constexpr char hexChar(std::string_view bits)