ATLAS Offline Software
Loading...
Searching...
No Matches
binStrToHexStr.h
Go to the documentation of this file.
1
2/*
3 Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
4*/
5
6#ifndef GLOBALSIM_BINSTRTOHEXSTR_H
7#define GLOBALSIM_BINSTRTOHEXSTR_H
8
9#include <algorithm>
10#include <string>
11
12namespace GlobalSim {
13
14
15 char hex_char(std::string::size_type begin,
16 std::string::size_type end,
17 const std::string& s) {
18 auto place_val{1U};
19 for (auto i{begin+1}; i != end; ++i) {
20 place_val *= 2;
21 }
22
23 auto val{0U};
24 for (std::size_t i{begin}; i != end; ++i) {
25 if (s[i] == '1') {val += place_val;}
26 place_val /= 2;
27 }
28
29 if (val < 10) {
30
31 return char('0' + val);
32 }
33
34 return char('a' + val-10);
35 }
36
37 std::string binStrToHexStr(std::string s) {
38
39 if (s.size() == 0) {return "";}
40
41
42 bool header{false};
43
44 if ((s.starts_with("0b") or s.starts_with("0B")) and s.size() >=2){
45 if (s.size() == 2) {return "";};
46 header = true;
47 }
48
49 const std::string::size_type offset = header ? 2:0;
50 const auto sz = s.size()-offset;
51
52
53 auto is_bin_char = [](const auto& c) {return c == '0' or c == '1';};
54
55 if (!std::all_of(std::cbegin(s)+offset, std::cend(s), is_bin_char)) {
56 throw std::out_of_range("ss contains non-binary char");
57 }
58
59 const auto n_ragged = sz - 4*(sz/4);
60
61 std::string result;
62 result.reserve (n_ragged ? 1+(sz)/4 : (sz)/4);
63
64
65 std::string::size_type start{offset};
66 std::string::size_type stop{offset+n_ragged};
67
68 if (n_ragged) {result.push_back(hex_char(start, stop, s));}
69
70 start = offset+n_ragged;
71 stop = start + 4;
72
73 if (stop > s.size()) {return result;}
74
75
76 for (auto i = start; i != s.size(); i += 4) {
77 result.push_back(hex_char(i, i+4, s));
78
79 start = stop;
80 stop += 4;
81 }
82
83 return result;
84
85 }
86}
87#endif
static Double_t sz
AlgTool that to test whether expected the TIP values generated by data supplied by eEmMultTestBench c...
char hex_char(std::string::size_type begin, std::string::size_type end, const std::string &s)
std::string binStrToHexStr(std::string s)