[erlang-questions] Help! a log dump function from C.

Tony Rogvall tony@REDACTED
Wed Apr 22 09:16:53 CEST 2009


I just needed one myself ;-)


dump(Binary) ->
     dump(0, Binary).

dump(A, <<B:16/binary,Rest/binary>>) ->
     A1 = dump_chunk(A, B),
     dump(A1, Rest);
dump(A, B) ->
     dump_chunk(A, B).

dump_chunk(A, B) ->
     Xs = [io_lib:format("~2.16.0B ", [X]) || <<X>> <= B ],
     Cs = [(if C >= 126; C < $\s -> $.; true -> C end) || <<C>> <= B],
     io:format("~8.16.0B: ~-48s- ~s\n", [A,Xs,Cs]),
     A+size(B).

You can modify this if you want to avoid one extra line when binary  
size is a multiple of 16
It worked nicely on my jpeg file ....

/Tony



On 22 apr 2009, at 02.03, feiman wrote:

> hi,All
>   I have a function from C,which print out detail hex information
> about a buffer,who can help me "translate" it into Erlang?
>
> when I run
> 	const char *teststr = "teststr1234567890abcd";
>
> 	dump_hex((const unsigned char *)teststr,strlen(teststr));
>
> it print out
>
> 00000000: 74 65 73 74 73 74 72 31 32 33 34 35 36 37 38 39 -
> teststr123456789
> 00000010: 30 61 62 63 64                                  - 0abcd
>
> thanks all in advance
>
> void dump_hex( const unsigned char *buf, int len)
> {
> 	int i;
> 	int nlocal;
> 	const unsigned char *pc;
> 	char *out;
> 	const unsigned char *start;
> 	char c;
> 	char line[100];
>
> 	start = buf;
>
> 	while (len > 0)
> 	{
> 		sprintf(line, "%08x: ", buf - start);
> 		out = line + 10;
>
> 		for (i = 0, pc = buf, nlocal = len; i < 16; i++, pc++)
> 		{
> 			if (nlocal > 0)
> 			{
> 				c = *pc;
>
> 				*out++ = NIBBLE((c >> 4) & 0xF);
> 				*out++ = NIBBLE(c & 0xF);
>
> 				nlocal--;
> 			}
> 			else
> 			{
> 				*out++ = ' ';
> 				*out++ = ' ';
> 			}			/* end else */
>
> 			*out++ = ' ';
> 		}			/* end for */
>
> 		*out++ = '-';
> 		*out++ = ' ';
>
> 		for (i = 0, pc = buf, nlocal = len;
> 			(i < 16) && (nlocal > 0);
> 			i++, pc++, nlocal--)
> 		{
> 			c = *pc;
>
> 			if ((c < ' ') || (c >= 126))
> 			{
> 				c = '.';
> 			}
>
> 			*out++ = c;
> 		}			/* end for */
>
> 		*out++ = 0;
>
> 		llog(L_NOTICE,"%s", line);
>
> 		buf += 16;
> 		len -= 16;
> 	}				/* end while */
> }				/* end dump */
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list