Question

im having a problem with __int64 and %I64u. or may be there is a problem with my formula. i am trying to mimic the output below. but there is a weird thing happen in some line items. i cant understand what happened since others were printed fine.

NOTE: the main source of these list are from binary raw data. so i fetched it from hex and trying to convert it in __int64. my list consist of 120 line items which outputs well up to line 73 and fail from line 74 with expected value of 2276812558 and displayed 18446744071691396878. From line 74 up to line 120 results are intermittent. others are ok and other lines fail.

anyone help??

SOURCE:

74  2276812558     <-- expected output
...
110 88343310421     <-- expected output
111 101677534814    <-- expected output
112 116372862414    
113 132547934111    <-- expected output
114 150330130721
115 169856101434    <-- expected output
116 193905458276    
117 220253625665    
118 249089120712    <-- expected output
119 280613529205    
120 315042247217

here is my code:

    longint =  (__int64)((col[3] << 24) | (col[2] << 16) | (col[1] << 8)) | ((col[0]) | (__int64)((col[7] << 56) | (col[6] << 48) | (col[5] << 40) | (col[4] << 32)) << 32);
sprintf(longintbuf,"%I64u", longint );

.OUTPUT GENERATED

74  18446744071691396878    <-- err
...
110 18446744071858548821    <-- err
111 18446744072307871326    <-- err
112 116372862414    
113 18446744073113499551    <-- err
114 150330130721    
115 18446744071766961210    <-- err
116 193905458276    
117 220253625665    
118 18446744073690569160    <-- err
119 280613529205    
120 315042247217
Was it helpful?

Solution

if col isn't an array of 64-bit types, your shifts are causing undefined behaviour. Cast before shifting:

(__int64)col[7] << 56

It's also undefined behaviour if the shift would cause a sign change, so be careful for that when using signed types (like you are).

From C11 6.5.7 Bitwise shift operators (emphasis mine):

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. ... If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top