将char数据转换成hex的格式

有时候,我们需要将char型的数据,转换成hex的形式,啥都不说,直接上代码。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>

#define CHAR_FILE	"./char.txt"
#define HEX_FILE	"./hex.txt"

int main( int argc, char** argv )
{
	int	char_fd = 0;
	int	hex_fd	= 0;

	int	read_ret	= 0;
	int	send_len	= 0;
	int	rcv_len		= 0;
	int	hex_len		= 0;

	int		ret		= 0;
	unsigned char	*send_buffer	= NULL;
	unsigned char	*raw_buffer	= NULL;

	char_fd = open( CHAR_FILE, O_RDWR | O_NONBLOCK );

	if ( char_fd < 0 )
	{
		printf( "char file open fail\n" );
		close( char_fd );
		return(0);
	}

	hex_fd = open( HEX_FILE, O_RDWR | O_NONBLOCK );

	if ( hex_fd < 0 )
	{
		printf( "hex file open fail\n" );
		close( hex_fd );
		return(0);
	}

	printf( "**************************\n" );
	printf( "********start ipc test****\n" );
	printf( "**************************\n" );

	send_len = lseek( char_fd, 0L, SEEK_END );
	lseek( char_fd, 0L, SEEK_SET );
	printf( "char.txt len = %d\n", send_len );

	send_buffer = (unsigned char *) malloc( send_len );
	if ( send_buffer == NULL )
	{
		printf( "send_buffer malloc error\n" );
		close( char_fd );
		close( hex_fd );
		return(-1);
	}

	memset( send_buffer, 0, (size_t) send_len );

	do
	{
		rcv_len = read( char_fd, send_buffer, send_len );
		if ( rcv_len < 0 )
		{
			printf( "read fail\n" );
			free( send_buffer );
			close( char_fd );
			close( hex_fd );
			return(-1);
		}
	}
	while ( rcv_len == 0 );

	printf( "have readed char.txt len = %d\n", rcv_len );
	hex_len		= rcv_len / 2;
	raw_buffer	= (unsigned char *) malloc( hex_len );
	if ( raw_buffer == NULL )
	{
		printf( "raw_buffer malloc error\n" );
		close( char_fd );
		close( hex_fd );
		free( send_buffer );
		return(-1);
	}

	int i = 0;
	for ( i = 0; i < hex_len; i++ )
	{
		sscanf( send_buffer + i * 2, "%2X", raw_buffer + i );
	}

	free( send_buffer );

	ret = write( hex_fd, raw_buffer, hex_len );
	if ( ret < 0 )
	{
		printf( "write fail\n" );
		free( raw_buffer );
		close( char_fd );
		close( hex_fd );
		return(-1);
	}
	printf( "have write len = %d\n", ret );

	printf( "**************************\n" );
	printf( "********end ipc test******\n" );
	printf( "**************************\n" );

	lseek( hex_fd, 0L, SEEK_SET );

	free( raw_buffer );
	close( hex_fd );
	close( char_fd );
	return(0);
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页