How this function f1() will execute? - c

#include <stdio.h>
void f1(char* str, int index)
{
*(str + index) &= ~32;
}
int main()
{
char arr[] = "gatecsit";
f1(arr, 0);
printf("%s", arr);
return 0;
}
How is function f1() working?
Being specific *(str + index) &= ~32; this one....
thanks

The expression
*(str + index)
is equivalent to
str[index]
So the character at position index is changed the following way
*(str + index) &= ~32;
In the ASCII table lower case letters differ from upper case letters by having one more set bit. For example the lower case letter 'a' has the code in hex 61 while the upper case letter 'A" has the code in hex 41. So the difference is equal to the value in hex 20 that in decimal is equal to 32.
So the original expression resets the corresponding bit in the character to 0 converting a lower case letter to the upper case letter.

I think f1() capitalizes the first letter of the string by exploiting a property of ASCII that means that corresponding lower and upper-case letters differ by 32. For example the code for 'A' is 65, while that for 'a' is 97. The '&= ~32' bit of the code will turn of bit-5 of the ASCII representation of the character str[index], which should turn the 'g' into 'G'. This should be fine for strings that contain only ordinary letters, but will have strange effects on digits and punctuation characters.

The code removes 1 bit from the character
effectively subtracting 32 from the byte or 0x20.
#include <stdio.h>
#include <string.h>
void f1(char* str, int index)
{
// The code removes 1 bit from the character at the position `str[index]`
// effectively subtracting 32 from that character
// Capital letters in ASCII are apart by 32 (0x20) from small letters
// Since 'a' = 0x61 and 'A' = 0x41 'a' - 32 = 'A'
// Since 'b' = 0x62 and 'B' = 0x42 'b' - 32 = 'B'
// `~` is a binary negation operator 0 -> 1; 1 -> 0
// `&` is a binary AND
// x &= y; is equivalent to x = x & y;
// ~0x20 = 0b11011111
*(str + index) &= ~0x20; // 0x20 = 32;
}
int main()
{
int i;
char arr[] = "gatecsit";
size_t len = strlen(arr);
for(i = 0; i< len; i++)
printf(" %c " , arr[i]);
printf("\n");
for(i = 0; i< len; i++)
printf(" %X" , arr[i]);
printf("\n");
// convert all letters:
for(i = 0; i< len; i++)
f1(arr, i);
printf("\n");
for(i = 0; i< len; i++)
printf(" %c " , arr[i]);
printf("\n");
for(i = 0; i< len; i++)
printf(" %X" , arr[i]);
return 0;
}
Output:
The small and capital are letters apart by 0x20 (or 32 decimal).
This can be clearly seen from this printout:
g a t e c s i t
67 61 74 65 63 73 69 74
G A T E C S I T
47 41 54 45 43 53 49 54

Related

Why is "0" "1" sometimes printed as a character and sometimes as ASCII 48/49?

I noticed this when I was writing code.
To xor the elements in the character array, why do some display 0/1 and some display ASCII? How do I get them all to behave like number 0 or 1?
In function XOR, I want to xor the elements in two arrays and store the result in another array.
In main, I do some experiments.
And by the way, besides printing the results, I want to do 0 1 binary operations. Such as encryption and decryption.
Here is a piece of C code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int XOR(char *u, char *w, char *v)
{
for(int i = 0; i < 16; i++)
{
u[i] = w[i] ^ v[i];
}
return 0;
}
int PrintList(char *list, int n)
{
for(int i = 0; i < n; i++)
{
printf("%d", list[i]);
}
return 0;
}
int main()
{
char u[17] = "";
char w[17] = "0001001000110100";
char v[17] = "0100001100100001";
XOR(u, w, v);
PrintList(u, 16);
printf("\n");
char w2[17] = "1000110011101111";
XOR(u, w2, v);
PrintList(u, 16);
printf("\n");
char v2[17] = "1111111011001000";
XOR(u, w2, v2);
PrintList(u, 16);
printf("\n");
char x[17] = "0101101001011010";
XOR(u, x, u);
PrintList(u, 16);
printf("\n");
memcpy(w, u, 16);
XOR(u, w, v);
PrintList(u, 16);
printf("\n");
return 0;
}
The result
0101000100010101
1100111111001110
0111001000100111
48484948494848484849494949494849
0110101101011100
Process returned 0 (0x0) execution time : 0.152 s
Press any key to continue.
Well, change my declarations from char to unsigned char, maybe due to printf("%d", list[i]);The print results no changes. Change to printf("%c", list[i]);The print results:
0010100001111101
Process returned 0 (0x0) execution time : 0.041 s
Press any key to continue.
Character '0' is ‭00110000‬ in binary. '1' is 00110001.
'0' ^ '0' = 00000000 (0)
'0' ^ '1' = 00000001 (1)
'1' ^ '1' = 00000000 (0)
But then you reuse the u array.
'0' ^ 0 = 0011000 (48)
'0' ^ 1 = 0011001 (49)
'1' ^ 0 = 0011001 (49)
'1' ^ 1 = 0011000 (48)
These are strings so you initially have the ASCII codes 48 (0011 0000) and 49 (0011 0001). The ^ operator is bitwise XOR so the result of two operands with the values 48 and 49 can either be 0 or 1. When you print that result as integer, you get 0 or 1 as expected.
If you later use the result of that operation though, you no longer have an array of ASCII codes, but an array of integers with the value 0 or 1. If you XOR that one with an array that is still an ASCII code array, for example 0011 0000 ^ 0, you will get the result 0011 0000, not 0. And so printf gives you 48 etc.

How to convert string of hex to hex in C? [duplicate]

I have a char[] that contains a value such as "0x1800785" but the function I want to give the value to requires an int, how can I convert this to an int? I have searched around but cannot find an answer. Thanks.
Have you tried strtol()?
strtol - convert string to a long integer
Example:
const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);
In case the string representation of the number begins with a 0x prefix, one must should use 0 as base:
const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);
(It's as well possible to specify an explicit base such as 16, but I wouldn't recommend introducing redundancy.)
Or if you want to have your own implementation, I wrote this quick function as an example:
/**
* hex2int
* take a hex string and convert it to a 32bit number (max 8 hex digits)
*/
uint32_t hex2int(char *hex) {
uint32_t val = 0;
while (*hex) {
// get current character then increment
uint8_t byte = *hex++;
// transform hex character to the 4bit equivalent number, using the ascii table indexes
if (byte >= '0' && byte <= '9') byte = byte - '0';
else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;
// shift 4 to make space for new digit, and add the 4 bits of the new digit
val = (val << 4) | (byte & 0xF);
}
return val;
}
Something like this could be useful:
char str[] = "0x1800785";
int num;
sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num);
Read man sscanf
Assuming you mean it's a string, how about strtol?
Use strtol if you have libc available like the top answer suggests. However if you like custom stuff or are on a microcontroller without libc or so, you may want a slightly optimized version without complex branching.
#include <inttypes.h>
/**
* xtou64
* Take a hex string and convert it to a 64bit number (max 16 hex digits).
* The string must only contain digits and valid hex characters.
*/
uint64_t xtou64(const char *str)
{
uint64_t res = 0;
char c;
while ((c = *str++)) {
char v = (c & 0xF) + (c >> 6) | ((c >> 3) & 0x8);
res = (res << 4) | (uint64_t) v;
}
return res;
}
The bit shifting magic boils down to: Just use the last 4 bits, but if it is an non digit, then also add 9.
One quick & dirty solution:
// makes a number from two ascii hexa characters
int ahex2int(char a, char b){
a = (a <= '9') ? a - '0' : (a & 0x7) + 9;
b = (b <= '9') ? b - '0' : (b & 0x7) + 9;
return (a << 4) + b;
}
You have to be sure your input is correct, no validation included (one could say it is C). Good thing it is quite compact, it works with both 'A' to 'F' and 'a' to 'f'.
The approach relies on the position of alphabet characters in the ASCII table, let's peek e.g. to Wikipedia (https://en.wikipedia.org/wiki/ASCII#/media/File:USASCII_code_chart.png). Long story short, the numbers are below the characters, so the numeric characters (0 to 9) are easily converted by subtracting the code for zero. The alphabetic characters (A to F) are read by zeroing other than last three bits (effectively making it work with either upper- or lowercase), subtracting one (because after the bit masking, the alphabet starts on position one) and adding ten (because A to F represent 10th to 15th value in hexadecimal code). Finally, we need to combine the two digits that form the lower and upper nibble of the encoded number.
Here we go with same approach (with minor variations):
#include <stdio.h>
// takes a null-terminated string of hexa characters and tries to
// convert it to numbers
long ahex2num(unsigned char *in){
unsigned char *pin = in; // lets use pointer to loop through the string
long out = 0; // here we accumulate the result
while(*pin != 0){
out <<= 4; // we have one more input character, so
// we shift the accumulated interim-result one order up
out += (*pin < 'A') ? *pin & 0xF : (*pin & 0x7) + 9; // add the new nibble
pin++; // go ahead
}
return out;
}
// main function will test our conversion fn
int main(void) {
unsigned char str[] = "1800785"; // no 0x prefix, please
long num;
num = ahex2num(str); // call the function
printf("Input: %s\n",str); // print input string
printf("Output: %x\n",num); // print the converted number back as hexa
printf("Check: %ld = %ld \n",num,0x1800785); // check the numeric values matches
return 0;
}
Try below block of code, its working for me.
char p[] = "0x820";
uint16_t intVal;
sscanf(p, "%x", &intVal);
printf("value x: %x - %d", intVal, intVal);
Output is:
value x: 820 - 2080
So, after a while of searching, and finding out that strtol is quite slow, I've coded my own function. It only works for uppercase on letters, but adding lowercase functionality ain't a problem.
int hexToInt(PCHAR _hex, int offset = 0, int size = 6)
{
int _result = 0;
DWORD _resultPtr = reinterpret_cast<DWORD>(&_result);
for(int i=0;i<size;i+=2)
{
int _multiplierFirstValue = 0, _addonSecondValue = 0;
char _firstChar = _hex[offset + i];
if(_firstChar >= 0x30 && _firstChar <= 0x39)
_multiplierFirstValue = _firstChar - 0x30;
else if(_firstChar >= 0x41 && _firstChar <= 0x46)
_multiplierFirstValue = 10 + (_firstChar - 0x41);
char _secndChar = _hex[offset + i + 1];
if(_secndChar >= 0x30 && _secndChar <= 0x39)
_addonSecondValue = _secndChar - 0x30;
else if(_secndChar >= 0x41 && _secndChar <= 0x46)
_addonSecondValue = 10 + (_secndChar - 0x41);
*(BYTE *)(_resultPtr + (size / 2) - (i / 2) - 1) = (BYTE)(_multiplierFirstValue * 16 + _addonSecondValue);
}
return _result;
}
Usage:
char *someHex = "#CCFF00FF";
int hexDevalue = hexToInt(someHex, 1, 8);
1 because the hex we want to convert starts at offset 1, and 8 because it's the hex length.
Speedtest (1.000.000 calls):
strtol ~ 0.4400s
hexToInt ~ 0.1100s
This is a function to directly convert hexadecimal containing char array to an integer which needs no extra library:
int hexadecimal2int(char *hdec) {
int finalval = 0;
while (*hdec) {
int onebyte = *hdec++;
if (onebyte >= '0' && onebyte <= '9'){onebyte = onebyte - '0';}
else if (onebyte >= 'a' && onebyte <='f') {onebyte = onebyte - 'a' + 10;}
else if (onebyte >= 'A' && onebyte <='F') {onebyte = onebyte - 'A' + 10;}
finalval = (finalval << 4) | (onebyte & 0xF);
}
finalval = finalval - 524288;
return finalval;
}
I have done a similar thing before and I think this might help you.
The following works for me:
int main(){
int co[8];
char ch[8];
printf("please enter the string:");
scanf("%s", ch);
for (int i=0; i<=7; i++) {
if ((ch[i]>='A') && (ch[i]<='F')) {
co[i] = (unsigned int) ch[i]-'A'+10;
} else if ((ch[i]>='0') && (ch[i]<='9')) {
co[i] = (unsigned int) ch[i]-'0'+0;
}
}
Here, I have only taken a string of 8 characters.
If you want you can add similar logic for 'a' to 'f' to give their equivalent hex values. Though, I haven't done that because I didn't need it.
I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h. Very simple to use :
unsigned hexdec (const char *hex, const int s_hex);
Before the first conversion intialize the array used for conversion with :
void init_hexdec ();
Here the link on github : https://github.com/kevmuret/libhex/
I like #radhoo solution, very efficient on small systems. One can modify the solution for converting the hex to int32_t (hence, signed value).
/**
* hex2int
* take a hex string and convert it to a 32bit number (max 8 hex digits)
*/
int32_t hex2int(char *hex) {
uint32_t val = *hex > 56 ? 0xFFFFFFFF : 0;
while (*hex) {
// get current character then increment
uint8_t byte = *hex++;
// transform hex character to the 4bit equivalent number, using the ascii table indexes
if (byte >= '0' && byte <= '9') byte = byte - '0';
else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;
// shift 4 to make space for new digit, and add the 4 bits of the new digit
val = (val << 4) | (byte & 0xF);
}
return val;
}
Note the return value is int32_t while val is still uint32_t to not overflow.
The
uint32_t val = *hex > 56 ? 0xFFFFFFFF : 0;
is not protected against malformed string.
Here is a solution building upon "sairam singh"s solution. Where that answer is a one to one solution, this one combines two ASCII nibbles into one byte.
// Assumes input is null terminated string.
//
// IN OUT
// -------------------- --------------------
// Offset Hex ASCII Offset Hex
// 0 0x31 1 0 0x13
// 1 0x33 3
// 2 0x61 A 1 0xA0
// 3 0x30 0
// 4 0x00 NULL 2 NULL
int convert_ascii_hex_to_hex2(char *szBufOut, char *szBufIn) {
int i = 0; // input buffer index
int j = 0; // output buffer index
char a_byte;
// Two hex digits are combined into one byte
while (0 != szBufIn[i]) {
// zero result
szBufOut[j] = 0;
// First hex digit
if ((szBufIn[i]>='A') && (szBufIn[i]<='F')) {
a_byte = (unsigned int) szBufIn[i]-'A'+10;
} else if ((szBufIn[i]>='a') && (szBufIn[i]<='f')) {
a_byte = (unsigned int) szBufIn[i]-'a'+10;
} else if ((szBufIn[i]>='0') && (szBufIn[i]<='9')) {
a_byte = (unsigned int) szBufIn[i]-'0';
} else {
return -1; // error with first digit
}
szBufOut[j] = a_byte << 4;
// second hex digit
i++;
if ((szBufIn[i]>='A') && (szBufIn[i]<='F')) {
a_byte = (unsigned int) szBufIn[i]-'A'+10;
} else if ((szBufIn[i]>='a') && (szBufIn[i]<='f')) {
a_byte = (unsigned int) szBufIn[i]-'a'+10;
} else if ((szBufIn[i]>='0') && (szBufIn[i]<='9')) {
a_byte = (unsigned int) szBufIn[i]-'0';
} else {
return -2; // error with second digit
}
szBufOut[j] |= a_byte;
i++;
j++;
}
szBufOut[j] = 0;
return 0; // normal exit
}
I know this is really old but I think the solutions looked too complicated. Try this in VB:
Public Function HexToInt(sHEX as String) as long
Dim iLen as Integer
Dim i as Integer
Dim SumValue as Long
Dim iVal as long
Dim AscVal as long
iLen = Len(sHEX)
For i = 1 to Len(sHEX)
AscVal = Asc(UCase(Mid$(sHEX, i, 1)))
If AscVal >= 48 And AscVal <= 57 Then
iVal = AscVal - 48
ElseIf AscVal >= 65 And AscVal <= 70 Then
iVal = AscVal - 55
End If
SumValue = SumValue + iVal * 16 ^ (iLen- i)
Next i
HexToInt = SumValue
End Function

String to ASCII Hex splitting in C

I am using C in Labwindows CVI 8.5.
I convert the float to ASCII Hex(this part is already done):
#include <stdio.h>
#include <string.h>
int main () {
char K_char[20], K_ASCII[20];
int a = 30; //30 degree Celsius
int i, len ;
float k = a + 273.15; //Temperature Celsius to Kelvin
sprintf(K_char, "%.2f", k); //Temperature K convert to char array
len = strlen(K_char);
for(i = 0; i<len; i++){
sprintf(K_ASCII+i*2, "%02X", K_char[i]); //char array convert to ASCII Hex
}
printf("%s\n", K_ASCII);
return(0);
}
The result from above code is 3330332E3135.
Now I want to extract each byte from above string like this :
a[0] = 0x33
a[1] = 0x30
a[2] = 0x33
a[3] = 0x2E
a[4] = 0x33
a[5] = 0x35
Can someone give me some advice?
Thanks for any help.
It seems you are over complicate it. You already have these values in K_char. Like
K_char[0] = 0x33
K_char[1] = 0x30
K_char[2] = 0x33
K_char[3] = 0x2E
K_char[4] = 0x31
K_char[5] = 0x35
Write a function that converts a single ASCII character '0' to '9' or 'A' to 'F' into the numeric equivalent.
Then loop over your ASCII format array like this:
size_t length = strlen(K_ASCII);
uint8_t hex [length/2+1];
for(size_t i=0; i<length/2; i++)
{
hex[i] = to_hex(K_ASCII[2*i]);
hex[i] <<= 4;
hex[i] += to_hex(K_ASCII[2*i+1]);
}

Converting ASCII string into binary to add Parity

I'm trying to convert ASCII strings into Binary so i can add Parity to it (Hamming Code). But the output is not right at all.
If i enter 'A' on the input it should return:
01000001
and i've tried it with 'B' but it doesn't return that
unsigned char bits[8];
for(int i = 8; i >= 1; i--){
i expect the output to be 01000001 for 'A'
but the actual output is 00100000
Same for ABC or B or C
i is off by one, so you are accessing elements bitC[8] to bitC[1] (even though bitC[8] is out of bounds), and you are printing bits 8 to 1 instead of bits 7 to 0.
Replace
for(int i = 8; i >= 1; i--){
with
for(int i = 8; i--; ){

Extract a bit sequence from a character

So I have an array of characters like the following {h,e,l,l,o,o}
so I need first to translate this to its bit representation, so what I would have is this
h = 01101000
e = 01100101
l = 01101100
l = 01101100
o = 01101111
o = 01101111
I need divide all of this bits in groups of five and save it to an array
so for example the union of all this characters would be
011010000110010101101100011011000110111101101111
And now I divide this in groups of five so
01101 00001 10010 10110 11000 11011 00011 01111 01101 111
and the last sequence should be completed with zeros so it would be 00111 instead. Note: Each group of 5 bits would be completed with a header in order to have 8 bits.
So I havent realized yet how to accomplish this, because I can extract the 5 bits of each character and get the representation of each character in binary as following
for (int i = 7; i >= 0; --i)
{
printf("%c", (c & (1 << i)) ? '1' : '0');
}
The problem is how to combine two characters so If I have two characters 00000001 and 11111110 when I divide in five groups I would have 5 bits of the first part of the character and for the second group I would have 3 bits from the last character and 2 from the second one. How can I make this combination and save all this groups in an array?
Assuming that a byte is made of 8 bits (ATTENTION: the C standard doesn't guarantee this), you have to loop over the string and play with bit operations to get it done:
>> n right shift to get rid of the n lowest bits
<< n to inject n times a 0 bit in the lowest position
& 0x1f to keep only the 5 lowest bits and reset the higer bits
| to merge high bits and low bits, when the overlapping bits are 0
This can be coded like this:
char s[]="helloo";
unsigned char last=0; // remaining bits from previous iteration in high output part
size_t j=5; // number of high input bits to keep in the low output part
unsigned char output=0;
for (char *p=s; *p; p++) { // iterate on the string
do {
output = ((*p >> (8-j)) | last) & 0x1f; // last high bits set followed by j bits shifted to lower part; only 5 bits are kept
printf ("%02x ",(unsigned)output);
j += 5; // take next block
last = (*p << (j%8)) & 0x1f; // keep the ignored bits for next iteration
} while (j<8); // loop if second block to be extracted from current byte
j -= 8;
}
if (j) // there are trailing bits to be output
printf("%02x\n",(unsigned)last);
online demo
The displayed result for your example will be (in hexadecimal): 0d 01 12 16 18 1b 03 0f 0d 1c, which corresponds exactly to each of the 5 bit groups that you have listed. Note that this code ads 0 right padding in the last block if it is not exactly 5 bits long (e.g. here the last 3 bits are padded to 11100 i.e. 0x1C instead of 111 which would be 0x0B)
You could easily adapt this code to store the output in a buffer instead of printing it. The only delicate thing would be to precalculate the size of the output which should be 8/5 times the original size, to be increased by 1 if it's not a multiple of 5 and again by 1 if you expect a terminator to be added.
Here is some code that should solve your problem:
#include <stdio.h>
#include <string.h>
int main(void)
{
char arr[6] = {'h', 'e', 'l', 'l', 'o', 'o'};
char charcode[9];
char binarr[121] = "";
char fives[24][5] = {{0}};
int i, j, n, numchars, grouping = 0, numgroups = 0;
/* Build binary string */
printf("\nCharacter encodings:\n");
for (j = 0; j < 6; j++) {
for (i = 0, n = 7; i < 8; i++, n--)
charcode[i] = (arr[j] & (01 << n)) ? '1' : '0';
charcode[8] = '\0';
printf("%c = %s\n", arr[j], charcode);
strcat(binarr, charcode);
}
/* Break binary string into groups of 5 characters */
numchars = strlen(binarr);
j = 0;
while (j < numchars) {
i = 0;
if ((numchars - j) < 5) { // add '0' padding
for (i = 0; i < (5 - (numchars - j)); i++)
fives[grouping][i] = '0';
}
while (i < 5) { // write binary digits
fives[grouping][i] = binarr[j];
++i;
++j;
}
++grouping;
++numgroups;
}
printf("\nConcatenated binary string:\n");
printf("%s\n", binarr);
printf("\nGroupings of five, with padded final grouping:\n");
for (grouping = 0; grouping <= numgroups; grouping++) {
for (i = 0; i < 5; i++)
printf("%c", fives[grouping][i]);
putchar(' ');
}
putchar('\n');
return 0;
}
When you run this as is, the output is:
Character encodings:
h = 01101000
e = 01100101
l = 01101100
l = 01101100
o = 01101111
o = 01101111
Concatenated binary string:
011010000110010101101100011011000110111101101111
Groupings of five, with padded final grouping:
01101 00001 10010 10110 11000 11011 00011 01111 01101 00111
#include <limits.h>
#include <stdio.h>
#define GROUP_SIZE 5
static int nextBit(void);
static int nextGroup(char *dest);
static char str[] = "helloo";
int main(void) {
char bits[GROUP_SIZE + 1];
int firstTime, nBits;
firstTime = 1;
while ((nBits = nextGroup(bits)) == GROUP_SIZE) {
if (!firstTime) {
(void) putchar(' ');
}
firstTime = 0;
(void) printf("%s", bits);
}
if (nBits > 0) {
if (!firstTime) {
(void) putchar(' ');
}
while (nBits++ < GROUP_SIZE) {
(void) putchar('0');
}
(void) printf("%s", bits);
}
(void) putchar('\n');
return 0;
}
static int nextBit(void) {
static int bitI = 0, charI = -1;
if (--bitI < 0) {
bitI = CHAR_BIT - 1;
if (str[++charI] == '\0') {
return -1;
}
}
return (str[charI] & (1 << bitI)) != 0 ? 1 : 0;
}
static int nextGroup(char *dest) {
int bit, i;
for (i = 0; i < GROUP_SIZE; ++i) {
bit = nextBit();
if (bit == -1) {
break;
}
dest[i] = '0' + bit;
}
dest[i] = '\0';
return i;
}

Resources