1 2 /* 3 * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27 #include <sstream> 28 #include <iomanip> 29 30 31 #include "hex.h" 32 33 34 void Hex::ascii(std::ostream &s, char c) { 35 if (::iscntrl(c)) { 36 if (c == '\a') { 37 s << "\\a "; 38 } else if (c == '\r') { 39 s << "\\r "; 40 } else if (c == '\n') { 41 s << "\\n "; 42 } else if (c == '\t') { 43 s << "\\t "; 44 } else { 45 s << "?? "; 46 } 47 } else { 48 s << c << " "; 49 } 50 } 51 52 void Hex::hex(std::ostream &s, char c) { 53 s << std::hex << std::setw(2) << std::setfill('0') << std::uppercase << (c & 0xff) << " "; 54 } 55 56 void Hex::bytes(std::ostream &s, char *p, size_t len, std::function<void(std::ostream &)> prefix) { 57 for (int i = 0; i < len; i++) { 58 if ((i % 16) == 0) { 59 if (i > 0) { 60 s << " "; 61 for (int c = i - 16; c < i; c++) { 62 ascii(s, p[c]); 63 } 64 } 65 s << std::endl; 66 prefix(s); 67 s << std::hex << std::setw(6) << std::setfill('0') << i << " "; 68 } 69 hex(s, p[i]); 70 } 71 72 if ((len % 16) == 0) { 73 s << " "; 74 for (int c = len - 16; c < len; c++) { 75 ascii(s, p[c]); 76 } 77 } else { 78 for (int v = len % 16; v < 16; v++) { 79 s << " "; 80 } 81 s << " "; 82 for (int c = len - (len % 16); c < len; c++) { 83 ascii(s, p[c]); 84 } 85 86 } 87 88 89 } 90 91 92 93