Unsigned Char Concat In C - c

im trying to convert a string message to hex value in C.
For example if i have a message like "abc" i want to have it by 162636 etc. My code is below. In this code, i have to do some concat operation to store them all but now i can store only 36. How can i store them?
unsigned char swapNibbles(char x)
{
return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );
}
void encode(char *message, char password[40]) {
unsigned char *reversedInput = malloc(strlen(message));
for (int i = 0; i < strlen(message); ++i) {
reversedInput=swapNibbles(message[i]);
}
printf("%2x TERS ",reversedInput);
//unsigned char *bitwiseMessage = (unsigned char*)message;
//printf("DÜZ %s\n",bitwiseMessage);
//printf("TERS %u\n", swapNibbles(bitwiseMessage));
}

Edit
My solution for hex-encoding: IDEOne
If you want your text to be hex-encoded, you will have to allocate twice as much space as the original message:
"abc" (3 bytes) ==> "616263" (6 bytes)
So you will need:
unsigned char *reversedInput = malloc(2*strlen(message)+1); // +1 for the final NULL-terminator
#include <string.h>
#include <malloc.h>
char* HexEncode(char* txt)
{
char* hexTxt = calloc(2*strlen(txt)+1,1);
for(char* p=hexTxt; *txt; p+=2)
{
sprintf(p, "%02x", *txt++);
}
return hexTxt;
}
int main() {
char* hexText = HexEncode("Hello World");
printf("Hexed is %s\n", hexText);
free(hexText);
return 0;
}
Output
Hexed is 48656c6c6f20576f726c64

Related

How do I read an already declared char string that is a unicode character as a hexadecimal 2 digit value?

Given two strings, I have to read the hexadecimal 2 digit values of each of their unicode values. disregarding the ASCII characters.
char * str1 = "⍺";
char * str2 = "alpha is ⍺, beta is β and mu is µ";
I tried to print these values using: printf("<%02x>\n", str1);, but it seems like the value is wrong (also did this with (unsigned char) and it didn't seem to work).
Output should be something like this
<e2>
<e8><a2><2e>
Here is my full code:
#include <stdio.h>
#include <string.h>
char *str1 = "⍺";
char *str2 = "alpha is ⍺, beta is β and mu is µ";
char *str3 = "β";
char *str4 = "µ";
int main(){
printf("<%x>\n", (unsigned char) * str1);
printf("<%x>", (unsigned char) * str1);
printf("<%x>", (unsigned char) * str3);
printf("<%x>\n", (unsigned char) * str4);
}
This code goes through the bytes of a string, and identifies the 'ASCII' characters (Unicode U+0000 .. U+007F), and usually doesn't print them, and for the Unicode characters from U+0080 upwards, prints out a <, the series of pairs of hex digits representing the character, and eventually a > at the end, with >< in the middle separating separate UTF8-encoded Unicode character. If you pass in one or more arguments, it prints the 'ASCII' characters too, but as themselves, not in the hex encoding.
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
static void dump_str(const char *s);
static bool print_ascii = false;
int main(int argc, char **argv)
{
const char *strings[] =
{
"⍺",
"alpha is ⍺, beta is β and mu is µ",
"At -37ºC, the £ and the € fall apart",
"嬀£Åºüÿ",
"⍺βµ",
};
enum { NUM_STRINGS = sizeof(strings) / sizeof(strings[0]) };
// Use argv - my compilation options don't allow unused parameters to a function
if (argc > 1 && argv[argc] == NULL)
print_ascii = true;
for (int i = 0; i < NUM_STRINGS; i++)
dump_str(strings[i]);
return 0;
}
static void dump_str(const char *s)
{
int c;
bool printing_ascii = true;
while ((c = (unsigned char)*s++) != '\0')
{
if (isascii(c))
{
if (!printing_ascii)
{
printing_ascii = true;
putchar('>');
}
if (print_ascii)
putchar(c);
}
else
{
if (printing_ascii)
{
printing_ascii = false;
putchar('<');
}
else
{
if ((c & 0xC0) != 0x80)
{
putchar('>');
putchar('<');
}
}
printf("%2x", c);
}
}
if (!printing_ascii)
putchar('>');
putchar('\n');
}
I called the program utf8-97; when run, it gave me:
$ ./utf8-97
<e28dba>
<e28dba><ceb2><c2b5>
<c2ba><c2a3><c2a0><e282ac>
<c3a5><c2ac><e282ac><c2a3><c385><c2ba><c3bc><c3bf>
<e28dba><ceb2><c2b5>
$ ./utf8-97 1
<e28dba>
alpha is <e28dba>, beta is <ceb2> and mu is <c2b5>
At -37<c2ba>C, the <c2a3><c2a0>and the <e282ac> fall apart
<c3a5><c2ac><e282ac><c2a3><c385><c2ba><c3bc><c3bf>
<e28dba><ceb2><c2b5>
$
The <c2a0> sequence is for a non-breaking space that I accidentally put/left in the code after the pound symbol £. I'm not sure if you'll get that if you copy the code from the answer.

How to construct and return a String in C? [duplicate]

This question already has answers here:
Function returning address of local variable error in C
(3 answers)
Closed 5 years ago.
I'm trying to construct and return a string in C, but running into a function returns address of local variable [-Wreturn-local-addr] compiler warning. I get that returning packet like I'm trying to do won't work, because packet is a pointer to the beginning of my chars of size packet_size, and that memory address isn't valid outside my function. I'm running on an AVR chip and don't want to use malloc. How should I go about solving this problem?
#include <stdio.h>
#include <string.h>
#include <stdint.h>
const char* construct_packet(const char* data);
void append(char* str, char c);
int main()
{
const char* my_packet = construct_packet("QERT");
printf("%s", my_packet);
return 0;
}
const char* construct_packet(const char* data)
{
const char training_chars[] = "___";
const char start_char = '>';
uint8_t checksum = 0;
for(uint16_t i = 0; i < strlen(data); i++) {
checksum += data[i];
}
const char checksum_char = checksum;
uint8_t packet_size = strlen(training_chars) + strlen(data) + 2; // Plus 2 for start byte and checksum byte
char packet[packet_size];
strcat(packet, training_chars);
append(packet, start_char);
strcat(packet, data);
append(packet, checksum_char);
return packet;
}
void append(char* str, char c)
{
str[strlen(str) + 1] = c;
}
If you don't want to use dynamic memory allocation, and don't want to use a static buffer, then you might try calculating and providing the memory buffer on the stack:
#include <stdio.h>
#include <string.h>
#include <stdint.h>
const char* construct_packet(const char* data, const char* training_chars, const char start_char, char* packet);
void append(char* str, char c);
int main()
{
const char data[] = "QERT";
const char training_chars[] = "___";
const char start_char = '>';
const uint8_t packet_size = strlen(training_chars) + strlen(data) + 2; // Plus 2 for start byte and checksum byte
char packet[packet_size];
const char* my_packet = construct_packet(data, training_chars, start_char, packet);
printf("%s", my_packet); // same as printf("%s", packet);
return 0;
}
const char* construct_packet(const char* data, const char* training_chars, const char start_char, char* packet)
{
uint8_t checksum = 0;
for(uint16_t i = 0; i < strlen(data); i++) {
checksum += data[i];
}
const char checksum_char = checksum;
strcat(packet, training_chars);
append(packet, start_char);
strcat(packet, data);
append(packet, checksum_char);
return packet;
}
void append(char* str, char c)
{
str[strlen(str) + 1] = c;
}
Phil Brubaker: If you don't want to use dynamic memory allocation, and don't want to use a static buffer, then you might try calculating and providing the memory buffer on the stack:
I will not say better, my implementation:
#include <stdio.h>
#include <string.h>
#include <stdint.h>
// in some header file
const char *construct_packet(char *packet, const char* data);
size_t size_packet(const char* data);
int main(void)
{
const char *data = "QERT";
size_t packet_size = size_packet(data);
char packet[packet_size];
construct_packet(packet, data);
printf("%s", packet);
}
// can be on a other file of course `training_chars` and `start_char` could be give in parameter
// of course cause there are static `size_packet()` and `contruct_packet()` must be in the same file
static const char * const training_chars = "___";
static const char start_char = '>';
size_t size_packet(const char* data)
{
// you forgot nul terminate byte
return sizeof training_chars - 1 + 1 + strlen(data) + 1 + 1;
}
const char *construct_packet(char *packet, const char* data)
{
size_t i = 0;
// I replace strcat because I supose you want speed note they are better method that this one
for (size_t j = 0; training_chars[j] != '\0'; j++) {
packet[i++] = training_chars[j];
}
packet[i++] = start_char;
// maybe this should be a char but you don't give information about checksum so I can't be sure
uint8_t checksum = 0;
for (size_t j = 0; data[j] != '\0'; j++) {
packet[i++] = data[j];
checksum += data[j];
}
packet[i++] = (char)checksum;
// you forgot nul terminate byte
packet[i] = '\0';
return packet;
}
Of course, you could just not calculate the size and give a maximum:
char packet[256];
construct_packet(packet, data, 256);

Printing out byte array as formatted text gives different outputs - C

I am trying to print out byte array as one byte at the time in hexadecimal format within for loop like this:
int my_function(void *data)
{
obuf = (str*)data;
int i;
for (i = 0; i < obuf->len; i++)
{
printf("%02X:", obuf->s[i]);
}
return 0;
}
str in this case is structure from Kamailio - review at http://www.asipto.com/pub/kamailio-devel-guide/#c05str
The expected output:
80:70:0F:80:00:00:96:00:1D:54:7D:7C:36:9D:1B:9A:20:BF:F9:68:E8:E8:E8:F8:68:98:E8:EE:E8:B4:7C:3C:34:74:74:64:74:69:2C:5A:3A:3A:3A:3A:3A:3A:32:24:43:AD:19:1D:1D:1D:1D:13:1D:1B:3B:60:AB:AB:AB:AB:AB:0A:BA:BA:BA:BA:B0:AB:AB:AB:AB:AB:0A:BA:BA:BA:BA:B9:3B:61:88:43:
What I am getting:
FFFFFF80:70:0F:FFFFFF80:00:00:FFFFFF96:00:1D:54:7D:7C:36:FFFFFF9D:1B:FFFFFF9A:20:FFFFFFBF:FFFFFFF9:68:FFFFFFE8:FFFFFFE8:FFFFFFE8:FFFFFFF8:68:FFFFFF98:FFFFFFE8:FFFFFFEE:FFFFFFE8:FFFFFFB4:7C:3C:34:74:74:64:74:69:2C:5A:3A:3A:3A:3A:3A:3A:32:24:43:FFFFFFAD:19:1D:1D:1D:1D:13:1D:1B:3B:60:FFFFFFAB:FFFFFFAB:FFFFFFAB:FFFFFFAB:FFFFFFAB:0A:FFFFFFBA:FFFFFFBA:FFFFFFBA:FFFFFFBA:FFFFFFB0:FFFFFFAB:FFFFFFAB:FFFFFFAB:FFFFFFAB:FFFFFFAB:0A:FFFFFFBA:FFFFFFBA:FFFFFFBA:FFFFFFBA:FFFFFFB9:3B:61:FFFFFF88:43:
Could someone please help me understand why there are some of bytes prefixed with FFFFFF and other aren't?
Thanks in advance
Looks like obuf->s[i] returns a signed value
You would need to cast it to a unsigned value to get rid of the FFF.. at start.
printf("%02X:", (unsigned char)(obuf->s[i]));
The problem appears with chars that have the most significant bit set (which are out of the proper pure ASCII set range 0-127). The key point is to consider chars as unsigned.
printf("%02X:", (unsigned char)(obuf->s[i]));
See this simple compilable repro C code:
#include <stdio.h>
#include <string.h>
struct _str {
char* s; /* pointer to the beginning of string (char array) */
int len; /* string length */
};
typedef struct _str str;
int my_function(void *data)
{
str* obuf;
int i;
obuf = (str*)data;
for (i = 0; i < obuf->len; i++) {
printf("%02X:", (unsigned char)(obuf->s[i]));
}
return 0;
}
int main(void)
{
char buf[2];
str s;
/* Test with ordinary ASCII string */
s.s = "Hello";
s.len = strlen(s.s);
my_function(&s);
printf("\n");
/* Test with char values with most significant bit set */
buf[0] = 0xF1;
buf[1] = 0x00;
s.s = buf;
s.len = 1;
my_function(&s);
return 0;
}
With MSVC, I get this output:
48:65:6C:6C:6F:
F1:

Passing multiple strings into a function

i am trying to read several strings into a function for processing. The instructions are to pass each string into the function (not create a 2d array of strings). The parameters must stay the same. Here is what i tried
#include <stdio.h>
#include <math.h>
void convert(char s[]), int counts[]);
int main(void)
{
int i = 0;
int d[2] = {};
char text0[] = "this IS a String 4 you.";
char text1[] = "This sample has less than 987654321 leTTers.";
while(i<2)
{
convert (text[i],d); """ this is wrong but i dont know how to correctly do this
i = i +1;
}
}
void convert(char s[]), int counts[])
{
printf("%s this should print text1 and text2", s );
}
So i have a couple of questions. Is there some sort of special character/operator similiar to the glob module in python that can correctly do the convert (text[i],d) part for me where i try to read in each string. Also the int counts[] purpose is to be filled in with the word and character count in the function. So if i fill in this array in function convertwill main also recognize it since i need to print the word/character count in main without returning the actual counts in convert
You could use temporary string pointer array to pass all strings:
char text1[] = "This sample has less than 987654321 leTTers.";
char const * texts[] = { text0, text1 };
convert (texts, 2, d);
}
void convert(char const * s[], size_t n, int counts[])
{
while(n--) {
*counts++ = strlen(*s);
printf("%s\n", *s++);
}
}
Some notes:
I added char const to function argument type. You should always do that when function does not change the string. If you need to change the string in function, just remove the const.
There is extra argument size_t n to pass array array element count to function. size_t can be found in stddef.h.
i think u lost a "(" in "void convert(char s[]), int counts[]);".
it should be void convert((char s[]), int counts[]);
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void convert(char s[], int counts[]);
int main(void){
int i = 0;
int d[2] = {0};
char text0[] = "this IS a String 4 you.";
char text1[] = "This sample has less than 987654321 leTTers.";
char *text[] = { text0, text1 };
for(i=0; i<2; ++i){
convert (text[i], d);
printf("%d, %d\n", d[0], d[1]);
}
}
void convert(char s[], int counts[]){
printf("%s\n", s );
{
char *temp = strdup(s);
char *word, *delimiter = " \t\n";//Word that are separated by space character.
int count_w=0, max_len=0;
for(word = strtok(temp, delimiter); word ; word = strtok(NULL, delimiter)){
int len = strlen(word);
if(max_len < len)
max_len = len;
++count_w;
}
counts[0] = count_w;
counts[1] = max_len;
free(temp);
}
}

simple XOR algorithm

Although I've used C++ a lot, I'm struggling with the C differences (mainly in strings).
Could you please show me a simple single function that encrypts a message with a key using XOR comparison.
Thank-you
EDIT:
Both the key and the message are char*
OK, I hacked around for a minute and came up with this (only vaguely tested):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * xorencrypt(char * message, char * key) {
size_t messagelen = strlen(message);
size_t keylen = strlen(key);
char * encrypted = malloc(messagelen+1);
int i;
for(i = 0; i < messagelen; i++) {
encrypted[i] = message[i] ^ key[i % keylen];
}
encrypted[messagelen] = '\0';
return encrypted;
}
int main(int argc, char * argv[]) {
char * message = "test message";
char * key = "abc";
char * encrypted = xorencrypt(message, key);
printf("%s\n", encrypted);
free(encrypted);
return 0;
}
Note that the function xorencrypt allocates and returns a new string, so it's the caller's responsibility to free it when done.
C is very close to Assembler, so this example is short:
while (*string)
*string++ ^= key;
assuming char *string; and char key.
For what it's worth, combine the answers from #ott-- & #Tim to form Xortron.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *xor(char *string, const char *key)
{
char *s = string;
size_t length = strlen(key), i = 0;
while (*s) {
*s++ ^= key[i++ % length];
}
return string;
}
int main(int argc, char **argv)
{
const char *key = "abc";
if (argc < 2) {
fprintf(stderr, "%s: no input\n", argv[0]);
return EXIT_FAILURE;
}
printf("%s\n", xor(xor(argv[1], key), key));
return EXIT_SUCCESS;
}

Resources