Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing hex value in C string?

Tags:

c

hex

binary

gdb

I have a string "SOMETHING /\xff" and I want to save the hex representation of 0xff into a char buffer. So I strncpy everything after the forward slash (/) into my buffer (let's call it buff).

However, when I use the gdb command print \x buff to view the contents of buff, it doesn't show 0xff. Any ideas as to what could be wrong? Is it possible that my forward slash is messing things up?

like image 214
Nosrettap Avatar asked Oct 17 '25 19:10

Nosrettap


1 Answers

I think your problem has to do with the way you're printing the variable in gdb. Take this simple program, compile as debug (-g if using gcc), and run and break at the first puts statement:

int main(void)
{
   char *ptr = "str \xff";
   char arr[] = "str \xff";
   puts(ptr);
   puts(arr);

   return 0;
}

If I try and print ptr the way you've mentioned, p /x ptr, it'll print the value of ptr (the address it's pointing to):

(gdb) p /x ptr
$1 = 0x4005f8

However if I do the same command for arr, I'll get:

(gdb) p /x arr
$2 = {0x73, 0x74, 0x72, 0x20, 0xff, 0x0}

That's because gdb can see that arr is of type char[6] and not char*. You can get the same results with the command p /x "str \xff", which is useful for testing things:

(gdb) p /x "str \xff"
$3 = {0x73, 0x74, 0x72, 0x20, 0xff, 0x0}


Now if you want to be able to print a certain amount of bytes from the address pointed to by a pointer, use the examine (x) memory command instead of print (p):

(gdb) x/6bx ptr
0x4005f8 <__dso_handle+8>:  0x73    0x74    0x72    0x20    0xff    0x00

That'll print 6 bytes in hex from the address pointed to by ptr. Try that with your buff variable and see how you go.


Alternatively, another thing you can try is:

(gdb) p /x (char[6])*ptr
$4 = {0x73, 0x74, 0x72, 0x20, 0xff, 0x0}

This will treat the char pointed to by ptr as the first element in an array of 6 chars, and will allow you to use the print command.

like image 83
AusCBloke Avatar answered Oct 20 '25 10:10

AusCBloke