blob: 872c5f3f0f003b7a7c67519335ef58edb1060299 [file] [log] [blame]
Andreas Huber72961232010-06-07 10:18:57 -07001/*
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
Andreas Huber6e4c5c42010-09-21 13:13:15 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "hexdump"
19#include <utils/Log.h>
20
Andreas Huber72961232010-06-07 10:18:57 -070021#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
30namespace android {
31
Andreas Huber84066782011-08-16 09:34:26 -070032static 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
42void hexdump(const void *_data, size_t size, size_t indent, AString *appendTo) {
Andreas Huber72961232010-06-07 10:18:57 -070043 const uint8_t *data = (const uint8_t *)_data;
44
45 size_t offset = 0;
46 while (offset < size) {
47 AString line;
48
Andreas Huber84066782011-08-16 09:34:26 -070049 appendIndent(&line, indent);
50
Andreas Huber72961232010-06-07 10:18:57 -070051 char tmp[32];
George Burgess IV2c9cb622016-02-29 13:39:17 -080052 snprintf(tmp, sizeof(tmp), "%08lx: ", (unsigned long)offset);
Andreas Huber72961232010-06-07 10:18:57 -070053
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 {
George Burgess IV2c9cb622016-02-29 13:39:17 -080063 snprintf(tmp, sizeof(tmp), "%02x ", data[offset + i]);
Andreas Huber72961232010-06-07 10:18:57 -070064 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
Andreas Huber84066782011-08-16 09:34:26 -070082 if (appendTo != NULL) {
83 appendTo->append(line);
84 appendTo->append("\n");
85 } else {
86 ALOGI("%s", line.c_str());
87 }
Andreas Huber72961232010-06-07 10:18:57 -070088
89 offset += 16;
90 }
91}
92
93} // namespace android
94