开发者

why is stroull() not working on a byte array with hexadecimal values?

here is some new test code with regards to my long issue. I figure that if i code my stuff as long long then that is half the battle in porting. the other half would be to make it into big endian so it can work on any 64 bit system. so i did the following:

#include <iostream>  
#include "byteswap.h"
#include "stdlib.h"

using namespace std;

int main()

{

char bytes[6] = {0x12,0x23,0xff,0xed,0x22,0x34};


//long *p_long = reinterpret_cast<long*> (bytes);


long long *p_long = reinterpret_cast<long long*> (bytes);


std::cout<<"hex="<<std::hex<<*p_long<<"LE"<<std::endl;


*p_long = bswap_64(*p_long);


std::cout<<"hex="<<std::hex<<*p_long<<"BE"<<std::endl;




return 0;

} 

this seems to me the simplest way of doing it. the problem now is at using bswap...i get the following output

hex=34563422edff2312LE hex=0BE

i g开发者_如何转开发ot all the bytes in the first as LE. but now it seems the 64bit swap function is not working. I think this would solve the issue i am having.

considering that i will be operating on a 20 byte array. i am also not sure how i would use pointers to do that. i am thinking i would need an array of long long pointers to get all this stuff stored and then call the byteswap on each to swap the values in each of those pointers. I personally have not done pointer incrementation via sizeof(long) to increment before.


Because the bytes 0xab,0x32,0x54,0xcd,0x44 do not represent a null-terminated string containing ASCII digits, which is what strtoll expects to see.

What are you trying to achieve? If you want to reinterpret the array as a long long, just do

signed long long test = *((signed long long *)bytes);

(except you need to add three more bytes, and also make the whole array 8-byte aligned).


It hasn;t failed - it has worked. It converts up to the first digit it cannot convert and character code AB hex is not a valid hex digit.


If you're expecting this program to output "ab3254cd44" then you're using the wrong function. bytes is not a string. It's just an array of 5 values.

Try this:

int bytes[5] = {0xab,0x32,0x54,0xcd,0x44};
cout << hex;
copy(&bytes[0], &bytes[sizeof(bytes)/sizeof(bytes[0])], ostream_iterator<int>(cout));

Program outputs:

ab3254cd44


0xab is not a valid hexadecimal ASCII character.


strtoll converts a cstring to an integer. bytes isn't a cstring, it's an array of 5 bytes. It returns 0 because the first byte isn't a hex character ('1' to '0' or 'a' to 'f').

The compiler treats all numbers you give it the same, no matter which base they're given in, so 'bytes' contains {171, 50, 84, 205, 68}. You don't need to do the conversion yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜