xref: /aosp_15_r20/frameworks/av/media/module/foundation/hexdump.cpp (revision ec779b8e0859a360c3d303172224686826e6e0e1)
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "hexdump"
19 #include <utils/Log.h>
20 
21 #include "hexdump.h"
22 
23 #include "ADebug.h"
24 #include "AString.h"
25 
26 #include <ctype.h>
27 #include <stdint.h>
28 #include <stdio.h>
29 
30 namespace android {
31 
appendIndent(AString * s,int32_t indent)32 static void appendIndent(AString *s, int32_t indent) {
33     static const char kWhitespace[] =
34         "                                        "
35         "                                        ";
36 
37     CHECK_LT((size_t)indent, sizeof(kWhitespace));
38 
39     s->append(kWhitespace, indent);
40 }
41 
hexdump(const void * _data,size_t size,size_t indent,AString * appendTo)42 void hexdump(const void *_data, size_t size, size_t indent, AString *appendTo) {
43     const uint8_t *data = (const uint8_t *)_data;
44 
45     size_t offset = 0;
46     while (offset < size) {
47         AString line;
48 
49         appendIndent(&line, indent);
50 
51         char tmp[32];
52         snprintf(tmp, sizeof(tmp), "%08lx:  ", (unsigned long)offset);
53 
54         line.append(tmp);
55 
56         for (size_t i = 0; i < 16; ++i) {
57             if (i == 8) {
58                 line.append(' ');
59             }
60             if (offset + i >= size) {
61                 line.append("   ");
62             } else {
63                 snprintf(tmp, sizeof(tmp), "%02x ", data[offset + i]);
64                 line.append(tmp);
65             }
66         }
67 
68         line.append(' ');
69 
70         for (size_t i = 0; i < 16; ++i) {
71             if (offset + i >= size) {
72                 break;
73             }
74 
75             if (isprint(data[offset + i])) {
76                 line.append((char)data[offset + i]);
77             } else {
78                 line.append('.');
79             }
80         }
81 
82         if (appendTo != NULL) {
83             appendTo->append(line);
84             appendTo->append("\n");
85         } else {
86             ALOGI("%s", line.c_str());
87         }
88 
89         offset += 16;
90     }
91 }
92 
93 }  // namespace android
94 
95