Code Snippets
C/C++ Code Snippets
C program to assign and copy hexadecimal values in character buffer.
By: IncludeHelp, On 04 OCT 2016
In this program we will learn how to assign and copy hexadecimal values into character buffer (string variable) in c programming language?
Here we will learn, how we can declare an unsigned char[] by assigning Hexadecimal values and how we can copy Buffer with Hexadecimal values using memcpy() into character buffer (string variable).
What is memcpy()?
memcpy() – it is a library function declared in string.h which copies memory area (a fixed number of bytes) from one buffer to another buffer.
Read about more memcpy()
Syntax
void *memcpy(void *dest, const void *src, size_t n);
void *dest - Destination buffer pointer
void *src - Source buffer pointer
size_t n - Number of bytes to copy
C program (Code snippet) – To Assign and Copy Hexadecimal values in Character Buffer (String)
Let’s consider the following example:
/*C program to assign and copy hexadecimal
values in character buffer.*/
#include <stdio.h>
#include <string.h>
int main(){
//through assignment
unsigned char hexV[]={0x05,0x0A,0xAF,0xFE,0x23};
int loop;
printf("Values through assigning...\n");
for(loop=0; loop<5; loop++){
printf("hexV[%d] : %02X\n",loop,hexV[loop]);
}
//through copy
memcpy(hexV,"\x10\xAA\x20\xFA\xAF",5);
printf("Values through copying...\n");
for(loop=0; loop<5; loop++){
printf("hexV[%d] : %02X\n",loop,hexV[loop]);
}
return 0;
}
Output
Values through assigning...
hexV[0] : 05
hexV[1] : 0A
hexV[2] : AF
hexV[3] : FE
hexV[4] : 23
Values through copying...
hexV[0] : 10
hexV[1] : AA
hexV[2] : 20
hexV[3] : FA
hexV[4] : AF