首页
社区
课程
招聘
[原创]android 16进制打印
2015-3-11 16:39 9103

[原创]android 16进制打印

2015-3-11 16:39
9103
主要是开发过程中在so里打印一块内存,让它以hexdump形式展示,分析内存数据。
打印效果:

--------- beginning of /dev/log/system

--------- beginning of /dev/log/main

D/andump( 6361): |00007530| 00 08 0E 00 00 01 00 52 4C 0E 00 00 58 0E 00 00 |.......RL...X...|

D/andump( 6361): |00007540| 01 00 55 58 0E 00 00 70 0E 00 00 01 00 52 70 0E |..UX...p.....Rp.|

--------------------------------------------------------------------------------------------------------------------
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <android/log.h>

#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "andump", __VA_ARGS__)

void hexdump(void *mem, unsigned len, unsigned mod){
  int x = 0, y = 0, line_count = 0;
  char line[1024];
  char ch[16] = {0};

  line_count = len / mod;
  line_count = len % mod ? line_count + 1 : line_count;
  
  for(x = 0; x < line_count; x++){
    memset(line, 0, sizeof(line));
    sprintf(ch, "|%08X| ", x * mod);
    strcat(line, ch);
    /*hex print*/
    for(y = mod * x; y < mod *(x+1); y++){
      if (y < len){
        sprintf(ch, "%02X ", ((unsigned char *)mem)[y]);
      }else{
        sprintf(ch, "00 ");
      }
      strcat(line, ch);
    }

    /*char print*/
    strcat(line, "|");
    for(y = mod * x; y < mod *(x+1); y++){
      unsigned ascii = (int)((unsigned char *)mem)[y];
      if ( ascii < 32 || 126 < ascii )
      {
        strcat(line, ".");
      }
      else
      {
        if ( ascii == 0x25 ){
          strcat(line, "%");
        }
        sprintf(ch, "%c", ascii);
        strcat(line, ch);
      }
    }
    y = 0;
    strcat(line, "|\n");
    LOGD(line);
  }
}

void usage(){
  printf("./andump.out [file]");
}

int main(int argc, const char *argv[]){
  int fd = -1;
  struct stat st = {0};
  char *buf = NULL;
  fd = open(argv[1], O_RDONLY);
  fstat(fd, &st);
  buf = (char *)malloc(st.st_size);
  read(fd, buf, st.st_size);
  hexdump(buf, st.st_size, 16);
  free(buf);
  close(fd);
  return 0;
}

阿里云助力开发者!2核2G 3M带宽不限流量!6.18限时价,开 发者可享99元/年,续费同价!

收藏
点赞0
打赏
分享
最新回复 (2)
雪    币: 2321
活跃值: (4028)
能力值: ( LV12,RANK:530 )
在线值:
发帖
回帖
粉丝
熊猫正正 9 2015-3-11 17:00
2
0
支持一下
雪    币: 59
活跃值: (185)
能力值: ( LV3,RANK:20 )
在线值:
发帖
回帖
粉丝
heartbeast 2015-3-12 09:52
3
0
支持支持
游客
登录 | 注册 方可回帖
返回