Write a C program that takes in a string of 256 hexadecimal digits and converts them to…
- User
Write a C program that takes in a string of 256 hexadecimal digits and converts them to an array of 128 bytes. Each byte is represented as a pair of digits in the input.
- Assistant
Here's a C program that takes a string of 256 hexadecimal digits and converts them to an array of 128 bytes:
#include <stdio.h> #include <stdlib.h> void hexToBytes(char* hexString, unsigned char* byteArray) { for (int i = 0, j = 0; i < 256; i += 2, ++j) { sscanf(hexString + i, "%2hhx", byteArray + j); } } int main() { char hexString[257]; // 256 digits + '\0' character unsigned char byteArray[128]; printf("Enter a string of 256 hexadecimal digits:\n"); fgets(hexString, sizeof(hexString), stdin); // Remove newline character from the end of the input if (hexString[strlen(hexString) - 1] == '\n') { hexString[strlen(hexString) - 1] = '\0'; } hexToBytes(hexString, byteArray); printf("Byte Array:\n"); for (int i = 0; i < 128; i++) { printf("%02X ", byteArray[i]); if ((i + 1) % 16 == 0) { printf("\n"); } } return 0; } - User
Could you do it without sscanf?
- Assistant
Certainly! Here's a modified version of the program that converts the hexadecimal string to a byte array without using
sscanf:#include <stdio.h> #include <stdlib.h> #include <string.h> unsigned char hexToByte(char* hexDigits) { unsigned char byte = 0; for (int i = 0; i < 2; ++i) { byte <<= 4; // Shift left by 4 bits if (hexDigits[i] >= '0' && hexDigits[i] <= '9') { byte |= hexDigits[i] - '0'; } else if (hexDigits[i] >= 'A' && hexDigits[i] <= 'F') { byte |= hexDigits[i] - 'A' + 10; } else if (hexDigits[i] >= 'a' && hexDigits[i] <= 'f') { byte |= hexDigits[i] - 'a' + 10; } else { printf("Invalid hexadecimal digit: %c\n", hexDigits[i]); exit(1); } } return byte; } void hexToBytes(char* hexString, unsigned char* byteArray) { for (int i = 0, j = 0; i < 256 && j < 128; i += 2, ++j) { byteArray[j] = hexToByte(hexString + i); } } int main() { char hexString[257]; // 256 digits + '\0' character unsigned char byteArray[128]; printf("Enter a string of 256 hexadecimal digits:\n"); fgets(hexString, sizeof(hexString), stdin); // Remove newline character from the end of the input if (hexString[strlen(hexString) - 1] == '\n') { hexString[strlen(hexString) - 1] = '\0'; } hexToBytes(hexString, byteArray); printf("Byte Array:\n"); for (int i = 0; i < 128; i++) { printf("%02X ", byteArray[i]); if ((i + 1) % 16 == 0) { printf("\n"); } } return 0; }